Created
May 9, 2018 18:16
-
-
Save jarhill0/9a5fb06a7e7b38e84549a2570e64653e to your computer and use it in GitHub Desktop.
This file contains hidden or 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
#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; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Adapted from my Java implementation :)