Skip to content

Instantly share code, notes, and snippets.

@jarhill0
Created May 9, 2018 18:16
Show Gist options
  • Save jarhill0/9a5fb06a7e7b38e84549a2570e64653e to your computer and use it in GitHub Desktop.
Save jarhill0/9a5fb06a7e7b38e84549a2570e64653e to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
int * merge(int* array, int length) {
if (length < 2)
return array;
int midpoint = length / 2;
int* front = merge(array, midpoint);
int* back = merge(array + midpoint, length - midpoint);
static int* out;
out = (int*) malloc(length * sizeof(int));
int outIndex = 0;
int frontIndex = 0;
int backIndex = 0;
while (frontIndex < midpoint && backIndex < length - midpoint) {
if (*(front + frontIndex) < *(back + backIndex)) {
*(out + outIndex) = *(front + frontIndex);
frontIndex++;
} else {
*(out + outIndex) = *(back + backIndex);
backIndex++;
}
outIndex++;
}
for (; frontIndex < midpoint; frontIndex++) {
*(out + outIndex) = *(front + frontIndex);
outIndex++;
}
for (; backIndex < length - midpoint; backIndex++) {
*(out + outIndex) = *(back + backIndex);
outIndex++;
}
return out;
}
int main() {
int myArray[] = {3, 1, 4, 2, 6};
int* result = merge(myArray, 5);
for (int i = 0; i < 5; i++)
printf("%d ", *(result + i));
printf("\n");
return 0;
}
@jarhill0
Copy link
Author

jarhill0 commented May 9, 2018

Adapted from my Java implementation :)

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