Last active
July 20, 2020 04:08
-
-
Save nicknapoli82/f704725066f4f9597c83a0f573e918ec to your computer and use it in GitHub Desktop.
Merge Sort Modified - Sort array in place
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
void merge_sort(int size, int (*comparator)(int, int), int arr[]); | |
int increasing(int a, int b); | |
int decreasing(int a, int b); | |
int main(void) { | |
// int test[7] = {5, 23, 7, 26, 17, 2, 9}; | |
int test[21] = {21, 20, 15, 17, 1, 7, 3, 1, 56, 48, | |
832, 38, 20, 19, 39, 40, 7, 38, 19, 28, 38}; | |
merge_sort(21, increasing, test); | |
for(int i = 0; i < 21; i++) { | |
printf("%i, ", test[i]); | |
} | |
printf("\n"); | |
} | |
int increasing(int a, int b) { | |
return a - b; | |
} | |
int decreasing (int a, int b) { | |
return b - a; | |
} | |
// Sorts based on what the comparator returns. | |
// < 0, > 0, or 0 for equality | |
void merge_sort(int size, int (*comparator)(int, int), int arr[]) { | |
// Thid defines sorting in increasing or decreasing order | |
if(size <= 1) | |
return; | |
int mid = size / 2; | |
int *lhs = &arr[0]; | |
int *rhs = &arr[mid]; | |
merge_sort(rhs - lhs, comparator, lhs); // left half | |
merge_sort(&arr[size] - rhs, comparator, rhs); // right half | |
int placeholder = 0; | |
while(lhs < &arr[mid] && rhs < &arr[size]) { | |
int comp = comparator(*lhs, *rhs); | |
if(comp == 0) { | |
if(lhs < &arr[mid]) | |
lhs++; | |
else if(rhs < &arr[size]) | |
rhs++; | |
else { | |
// Since both pointers are at the end of their own half | |
// We are done | |
break; | |
} | |
} | |
else if(comp < 0) { | |
lhs++; | |
while(lhs < &arr[mid] && comparator(*lhs, *rhs) < 0) { | |
lhs++; | |
} | |
} | |
else if(comp > 0) { | |
placeholder = *lhs; | |
*lhs = *rhs; | |
*rhs = placeholder; | |
lhs++; | |
int *temp_r = rhs; | |
while(temp_r < &arr[size - 1] && comparator(*temp_r, *(temp_r + 1)) > 0) { | |
placeholder = *temp_r; | |
*temp_r = *(temp_r + 1); | |
*(temp_r + 1) = placeholder; | |
temp_r++; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment