Skip to content

Instantly share code, notes, and snippets.

@gene-ressler
Last active October 9, 2022 22:08
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 gene-ressler/21c8a28979f5445a33d0db5277b6d28b to your computer and use it in GitHub Desktop.
Save gene-ressler/21c8a28979f5445a33d0db5277b6d28b to your computer and use it in GitHub Desktop.
Array merge sort
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void sort(int *a, int n) {
if (n <= 1) return;
int m = (n + 1) / 2;
sort(a, m);
sort(a + m, n - m);
int b[m];
for (int i = 0; i < m; ++i) b[i] = a[i];
int i = 0, ia = m, ib = 0;
while (i < ia && ia < n && ib < m) a[i++] = a[ia] < b[ib] ? a[ia++] : b[ib++];
while (ib < m) a[i++] = b[ib++];
}
// Optimization that avoids temp space and copying for sorted data.
void sort2(int *a, int n) {
if (n <= 1) return;
int m = (n + 1) / 2, k;
sort2(a, m);
sort2(a + m, n - m);
for (k = 0; k < m && a[k] <= a[m]; ++k) ; // Find a[0..k-1] already sorted.
int mb = m - k;
if (mb == 0) return;
int b[mb]; // Temp space for the unsorted chunk.
for (int i = k; i < m; ++i) b[i - k] = a[i];
int i = k, ia = m, ib = 0;
while (i < ia && ia < n && ib < mb) a[i++] = a[ia] < b[ib] ? a[ia++] : b[ib++];
while (ib < mb) a[i++] = b[ib++];
}
int main(void) {
int n = 100, a[n];
for (int i = 0; i < n; ++i) a[i] = rand();
sort(a, n);
for (int i = 0; i < n; ++i) printf("%d\n", a[i]);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment