Skip to content

Instantly share code, notes, and snippets.

@hackrio1
Created August 2, 2018 04:54
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save hackrio1/a11c8499ed68f5df6c30e53d1c3fe076 to your computer and use it in GitHub Desktop.
Save hackrio1/a11c8499ed68f5df6c30e53d1c3fe076 to your computer and use it in GitHub Desktop.
Merge sort - Code
#include <stdio.h>
// function to sort the subsection a[i .. j] of the array a[]
void merge_sort(int i, int j, int a[], int aux[]) {
if (j <= i) {
return; // the subsection is empty or a single element
}
int mid = (i + j) / 2;
// left sub-array is a[i .. mid]
// right sub-array is a[mid + 1 .. j]
merge_sort(i, mid, a, aux); // sort the left sub-array recursively
merge_sort(mid + 1, j, a, aux); // sort the right sub-array recursively
int pointer_left = i; // pointer_left points to the beginning of the left sub-array
int pointer_right = mid + 1; // pointer_right points to the beginning of the right sub-array
int k; // k is the loop counter
// we loop from i to j to fill each element of the final merged array
for (k = i; k <= j; k++) {
if (pointer_left == mid + 1) { // left pointer has reached the limit
aux[k] = a[pointer_right];
pointer_right++;
} else if (pointer_right == j + 1) { // right pointer has reached the limit
aux[k] = a[pointer_left];
pointer_left++;
} else if (a[pointer_left] < a[pointer_right]) { // pointer left points to smaller element
aux[k] = a[pointer_left];
pointer_left++;
} else { // pointer right points to smaller element
aux[k] = a[pointer_right];
pointer_right++;
}
}
for (k = i; k <= j; k++) { // copy the elements from aux[] to a[]
a[k] = aux[k];
}
}
int main() {
int a[100], aux[100], n, i, d, swap;
printf("Enter number of elements in the array:\n");
scanf("%d", &n);
printf("Enter %d integers\n", n);
for (i = 0; i < n; i++)
scanf("%d", &a[i]);
merge_sort(0, n - 1, a, aux);
printf("Printing the sorted array:\n");
for (i = 0; i < n; i++)
printf("%d\n", a[i]);
return 0;
}
@durryx
Copy link

durryx commented Feb 1, 2020

very well written code, compliments

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment