privatestaticvoidmerge(int a [] , int low , int middle , int high ) { // Copy both parts into the helper array for (inti= low ; i <= high ; i ++) { MERGE_HELPER [ i ] = a [ i ]; } inti= low ; intj= middle + 1; intk= low ; // Copy the smallest values from the left or the right side back to the original array while ( i <= middle && j <= high ) { if ( MERGE_HELPER [ i ] <= MERGE_HELPER [ j ]) { a [ k ] = MERGE_HELPER [ i ]; i ++; } else { a [ k ] = MERGE_HELPER [ j ]; j ++; } k ++; } // Copy the rest of the left side of the array into the targetarray while ( i <= middle ) { a [ k ] = MERGE_HELPER [ i ]; k ++; i ++; } // Copy the rest of the right side of the array into the target array while ( j <= high ) { a [ k ] = MERGE_HELPER [ j ]; k ++; j ++; } }
Code Sample 20: C Merge Sort for integers
1 2 3 4 5 6 7 8 9 10 11 12 13 14
voidmergeSort(int * array , int left , int right ) { int mid = ( left + right ) /2; /* We have to sort only when left < right because when left = right it is anyhow sorted */ if( left < right ) { /* Sort the left part */ mergeSort ( array , left , mid ) ; /* Sort the right part */ mergeSort ( array , mid +, right ) ; /* Merge the two sorted parts */ merge ( array , left , mid , right ) ; } }