Created
September 24, 2017 18:14
-
-
Save icyflame/a9d19018516cccd39076a0e2b6e0e660 to your computer and use it in GitHub Desktop.
Merge sort - something's WRONG
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 <stdlib.h> | |
#include <iostream> | |
using namespace std; | |
int * merge_sort(int *A, int begin, int end) { | |
if (end - begin <= 1) { | |
return A; | |
} | |
int middle = begin + (end - begin) / 2; | |
int *B = merge_sort(A, begin, middle); | |
int *C = merge_sort(A, middle, end); | |
int *result = (int *) malloc(sizeof(int) * (end - begin)); | |
int i = begin, j = middle, k = 0; | |
for (; i < middle && j < end; ) { | |
result[k++] = (C[j] < B[i]) ? C[j++] : B[i++]; | |
} | |
for (; i < (middle - begin); ++i) { | |
result[k++] = B[i++]; | |
} | |
for (; j < (end - middle); ++j) { | |
result[k++] = C[j++]; | |
} | |
for (i = begin; i < end; ++i) A[i] = result[i - begin]; | |
free(result); | |
return A; | |
} | |
int main() { | |
int *A, n; | |
cin >> n; | |
int i; | |
for (i = 0; i < n; ++i) { | |
cin >> A[i]; | |
} | |
for (i = 0; i < n; ++i) { | |
cout << A[i] << ", "; | |
} | |
cout << endl; | |
A = merge_sort(A, 0, n); | |
for (i = 0; i < n; ++i) { | |
cout << A[i] << ", "; | |
} | |
cout << endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment