Search code examples
javasortingcomparisonswapbubble-sort

Number of swaps and comparisons in Shaker/Cocktail sort -Java


I have looked at how to count swaps and comparisons for bubble sort and modified a shaker sort program to this:

 public void shakerSort(int a[])  // http://www.geeksforgeeks.org/cocktail-sort/
{
    boolean swapped = true;
    comparisons = 0;
    swaps = 0;
    int start = 0;
    int end = a.length;

    while (swapped==true)
    {         
        swapped = false;

        for (int i = start; i < end-1; ++i)
        {
          comparisons++; //count comparisons
          if (a[i] > a[i + 1])
          {
             int temp = a[i];
             a[i] = a[i+1];
             a[i+1] = temp;
             swapped = true;

             swaps++; //count swaps
          }
        }

        if (swapped==false)
        {
            break; 
        }

        swapped = false;

        end = end-1;

        for (int i = end-1; i >=start; i--)
        {
          comparisons++; //count comparisons
            if (a[i] > a[i+1])
            {
                int temp = a[i];
                a[i] = a[i+1];
                a[i+1] = temp;
                swapped = true;
                swaps++; //count swaps
            }
        }

        start = start+1;

    }

}

However, for an array of 100 elements where the number of comparisons should always be 4950 ( n(n-1)/2 ), it gives me a value that changes every time I run the program- and this value is always less than 4950.

Why does it do this, and how can I fix it?

(NOTE: The array is randomized each time the program is run)

Also, is the swap count okay?


Solution

  • Let's take example and understand changes in count:

    array[5] = { 2 , 1 , 3 , 4 , 5 }

    How many iterations should it take.?

    first, shaker sort will check from start and then from last in every iterations. count is 0 at start.

     2 , 1 , 3 , 4 , 5 --> count = 1
     ^   ^
     it will swap 2 and 1
     swap count++
    
     1 , 2 , 3 , 4 , 5  --> count = 2
                 ^   ^
     no swap
    

    the program will again check because the swap = true

     1 , 2 , 3 , 4 , 5 --> count = 3
         ^   ^
      no swap
    
     1 , 2 , 3 , 4 , 5  --> count = 4
             ^   ^
     no swap
    

    the program will end because now swap = false.


    Now lets take different array:

    array[5] = { 5 , 4 , 3 , 2 , 1 }

    for the same, Iterations will be much more that 4 iterations.!


    Hence, For same size array and different value, number of iterations will be different.!

    Note: swap count and iteration count is used perfect in the the program :)