#include #include void printArray(int A[], int size) { int i; for (i=0; i < size; i++) printf("%d ", A[i]); printf("\n"); } // Merges two subarrays of arr[]. // First subarray is arr[l..m] // Second subarray is arr[m+1..r] void merge(int arr[], int left, int middle, int right) { int i1, j1, k1; int n1 = middle - left + 1; int n2 = right - middle ; /* create temp arrays */ int L[n1], R[n2]; /* Copy data to temp arrays L[] and R[] */ for (i1 = 0; i1 < n1; i1++) L[i1] = arr[left + i1]; for (j1 = 0; j1 < n2; j1++) { int index ; //index = left ; index = middle + 1 + j1 ; //((middle+left )+ j1) ; printf( "index:%d\n" , index ) ; R[j1] = arr[ middle + 1 + j1 ] ; } /* Merge the temp arrays back into arr[l..r]*/ i1 = 0; // Initial index of first subarray j1 = 0; // Initial index of second subarray k1 = left; // Initial index of merged subarray while (i1 < n1 && j1 < n2) { if (L[i1] <= R[j1]) { arr[k1] = L[i1]; i1++; } else { arr[k1] = R[j1]; printf( "else j1:%d k1:%d right:%d\n" , j1, k1 ) ; j1++; } k1++; } /* Copy the remaining elements of L[], if there are any */ while (i1 < n1) { printf( "n1 j1:%d i1:%d right:%d\n" , j1, i1 ) ; arr[k1] = L[i1]; i1++; k1++; } /* Copy the remaining elements of R[], if there are any */ while (j1 < n2) { printf( "n2 j1:%d i1:%d right:%d\n" , j1, i1 ) ; arr[k1] = R[j1]; j1++; k1++; } printf( "left:%d middle:%d right:%d\n" , left, middle, right ) ; printArray(arr, 4); } /* l is for left index and r is right index of the sub-array of arr to be sorted */ void mergeSort(int arr[], int left, int right ) { if (left < right ) { // Same as (l+r)/2, but avoids overflow for // large l and h int middle = (left+right)/2 ; // Sort first and second halves mergeSort(arr, left, middle); mergeSort(arr, middle+1, right); merge(arr, left, middle, right); } } int main() { //int arr[] = {12, 11, 13, 5, 6, 7}; int arr[] = { 12, 11, 13, 5 }; int arr_size = sizeof(arr)/sizeof(arr[0]); printf("Given array is \n"); printArray(arr, arr_size); mergeSort(arr, 0, arr_size - 1); printf("\nSorted array is \n"); printArray(arr, arr_size); return 0; }