Programming with Passion

Make the best out of everything.

Thursday 17 March 2016

Exchange Sort

Exchange Sort
The exchange sort is similar to its cousin, the bubble sort, in that it compares elements of the array and swaps those that are not in their proper positions.  (Some people refer to the "exchange sort" as a "bubble sort".)  The difference between these two sorts is the manner in which they compare the elements. The exchange sort compares the first element with each following element of the array, making any necessary swaps.
 
When the first pass through the array is complete, the exchange sort then takes the second element and compares it with each following element of the array swapping elements that are out of order.  This sorting process continues until the entire array is ordered. 
Let's examine our same table of elements again using an exchange sort for descending order.  Remember, a "pass" is defined as one full trip through the array comparing and if necessary, swapping elements.
Array at beginning: 846976869491
After Pass #1:946976848691
After Pass #2:949169768486
After Pass #3: 949186697684
After Pass #4: 949186846976
After Pass #5 (done): 949186847669
The exchange sort, in some situations, is slightly more efficient than the bubble sort.  It is not necessary for the exchange sort to make that final complete pass needed by the bubble sort to determine that it is finished.

//Exchange Sort Function for Descending Order
void ExchangeSort(apvector <int> &num)
{
     int i, j;
     int temp;   // holding variable
     int numLength = num.length( );
     for (i=0; i< (numLength -1); i++)    // element to be compared
    {
          for(j = (i+1); j < numLength; j++)   // rest of the elements
         {
                if (num[i] < num[j])          // descending order
               {
                        temp= num[i];          // swap
                        num[i] = num[j];
                        num[j] = temp;
               }
          }
     }
     return;
}

No comments:

Post a Comment