Created
July 1, 2016 23:35
-
-
Save raunaqbn/e7912daa407577bf00591abfcb0fa1e4 to your computer and use it in GitHub Desktop.
Merge sort
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
void mergeArrays(int * arr, int l, int m, int r) | |
{ | |
// Compare element by element from arr[l:m] with arr[m:r] and accordingly move index within idividual arr | |
int lsize = m-l+1; // this will include the middle element | |
int rsize = r-m; | |
int L[lsize];R[rsize]; | |
for(int i=0; i < lsize; i++) | |
L[i] = arr[l+i]; | |
for(int i=0; i < rsize; i++) | |
R[i] = arr[m+j]; | |
int i = 0;j = 0;index = l; | |
while(i < lsize && j < rsize) | |
{ | |
if (L[i] <= R [j]) | |
{ | |
arr[k] = L[i]; | |
i++; | |
} | |
else | |
{ | |
arr[k] = R[j]; | |
j++; | |
} | |
k++; | |
} | |
while (i < lsize) | |
{ | |
arr[k] = L[i]; | |
i++;k++; | |
} | |
while (j < rsize) | |
{ | |
arr[k] = L[i]; | |
i++;k++; | |
} | |
} | |
void mergeSort(int *arr, int l, int r) | |
{ | |
// divide the arrays into left and right and then call merge on them to sort them | |
// Make sure that the l < r | |
if (l < r) | |
{ | |
m = (l+r)/2; | |
mergeSort(arr, l, m); | |
mergeSort(arr, m, r); | |
mergeArrays(arr,l,m,r); | |
} | |
} | |
int main() | |
{ | |
int arr[100] = {3,45,64,2,...}; | |
mergeSort(arr,0,100); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment