Click here to Skip to main content
15,885,031 members
Please Sign up or sign in to vote.
4.00/5 (1 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?

C#
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
Comments
YvesDaoust 3-Nov-12 18:56pm    
Are you kidding ? This code already does a decreasing number of swaps per pass.

1 solution

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.
C++
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.
 
Share this answer
 
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)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900