Exchange Sort
 

The exchange sort is very similar the bubble sort, in that it compares elements of the array and swaps those that are not in their proper positions.

The exchange sort compares the first element with each following element of the array, making any necessary swaps.

It then takes the second element and compares it with each following element of the array making necessary swaps, and so on until the 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: 84 69 76 86 94 91
After Pass #1: 94 69 76 84 86 91
After Pass #2: 94 91 69 76 84 86
After Pass #3: 94 91 86 69 76 84
After Pass #4: 94 91 86 84 69 76
After Pass #5 (done): 94 91 86 84 76 69

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 Method for Descending Order (integers)
public static void exchange_sort ( int [ ] a )
{
int i, j, temp; //be sure that the temp variable is the same "type" as the array
for ( i = 0; i < a.length - 1; i ++ )
{
for ( j = i + 1; j < a.length; j ++ )
{
if( a[ i ] < a[ j ] ) //sorting into descending order
{
temp = a[ i ]; //swapping
a[ i ] = a[ j ];
a[ j ] = temp;
}
}
}
}


When completed, the array will be in descending order and can be printed from main.

For ascending order, change the "if" inequality to >.

(c) Shilpa Sayura Foundation 2006-2017