Skip to content

Instantly share code, notes, and snippets.

@yucombinator
Created December 15, 2014 03:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yucombinator/f1ba8470a69c6160bb2e to your computer and use it in GitHub Desktop.
Save yucombinator/f1ba8470a69c6160bb2e to your computer and use it in GitHub Desktop.
void mergeS(int *a, int n, int *temp){
//base case
if (n <= 1) {
return;
}
//recursion stuff
mergeS(a, n / 2, temp);
mergeS(a + n/2, n - n / 2, temp);
int i = 0, j = n / 2, k = 0;
while (i < n / 2 && j < n) {
//basically compare the leftmost element to the middle of the list
//then if the smallest element is the leftmost element, put it as the first element of a temp list
//and vice versa
if (a[i] <= a[j]) {
temp[k] = a[i];
k++; i++;
}
else {
temp[k] = a[j];
k++; j++;
}
}
//Copy the rest (since the loop earlier terminates before all elements are copied
while (i < n / 2) {
temp[k] = a[i];
k++; i++;
}
while (j < n) {
temp[k] = a[j];
k++; j++;
}
//merge to the main list
for (i = 0; i < n; i++) {
a[i] = temp[i];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment