12,446,525 members (52,054 online)
Rate this:
Please Sign up or sign in to vote.
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]);
}
Console.ReadLine();
}

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 12:49pm
Comments
YvesDaoust 3-Nov-12 18:56pm

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

## 1 solution

Rate this:
Please Sign up or sign in to vote.

## 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
Comments
Birdmanjackj 3-Nov-12 20:00pm

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

Nice.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Top Experts
Last 24hrsThis month
 OriginalGriff 355 Richard Deeming 320 ppolymorphe 255 CPallini 165 Karthik Bangalore 150
 OriginalGriff 5,543 Karthik Bangalore 3,272 ppolymorphe 3,147 Maciej Los 2,832 Richard Deeming 2,580

Advertise | Privacy | Mobile
Web02 | 2.8.160811.3 | Last Updated 3 Nov 2012
Copyright © CodeProject, 1999-2016
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100