12,078,090 members (47,257 online)
Rate this:
See more:
Instead of making nine comparisons on every pass, I need help modifing the bubble sort to make eight comparisons on the second pass, seven on the third pass and so on. Then I need it to check at the end of each pass whether any swaps have been made. If none have been made, the data must already be in the proper order, so the application should terminate. If swaps have been made, at least one more pass is needed. What do I need to add or change to my code to do these modifications?

```namespace Enhanced_Bubble_Sort
{
class Program
{

static void Main(string[] args)
{
int[] unsortedArray = new int[] { 23, 7, 10, 138, 2098, 2, 0, -5 };
Console.WriteLine("UNSORTED");

for (int i = 0; i < unsortedArray.Length; i++)
{
Console.WriteLine(unsortedArray[i]);
}

int[] sortedArray = BubbleSort(unsortedArray);
Console.WriteLine("BUBBLE SORTED");
for (int i = 0; i < sortedArray.Length; i++)
{
Console.WriteLine(sortedArray[i]);
}
}

private static int[] BubbleSort(int[] unsortedArray)
{
int length =unsortedArray.Length;
for (int i = 0; i < length - 1; i++)
{
for (int j = 0; j < length - 1 - i; j++)
{
if(unsortedArray[j] > unsortedArray[j + 1])
{
int num = unsortedArray[j];
unsortedArray[j] = unsortedArray[j + 1];
unsortedArray[j + 1] = num;
}
}
}
return unsortedArray;

}

}
}```
Posted 3-Nov-12 13:49pm
YvesDaoust 3-Nov-12 18:56pm

Are you kidding ? This code already does a decreasing number of swaps per pass.

Rate this:

## Solution 1

To handle the "no swap" situation, here is my proposal:

When entering the outer loop, save the value of `i` in a temporary variable and set `i` to `length - 1` (this value will cause an exit at the next iteration). And in the body of the if test (i.e. when a swap is made), restore the value of `i`.
```Loop on i:
Save i
Set i to exit value
Loop on j:
if Out-of-order
Swap
Restore i
```
Beware that this is a non-classical solution, your teacher will be intrigued.
v2
Birdmanjackj 3-Nov-12 20:00pm

How would that look in my code?
YvesDaoust 4-Nov-12 8:26am

Nice.

Top Experts
Last 24hrsThis month
 Richard MacCutchan 400 Richard Deeming 280 Dave Kreskowiak 265 CHill60 200 OriginalGriff 195
 Dave Kreskowiak 3,026 OriginalGriff 3,000 Richard MacCutchan 2,539 CPallini 1,722 CHill60 1,579