Created
March 16, 2012 04:24
-
-
Save ryanohs/2048499 to your computer and use it in GitHub Desktop.
Merge Sort - C++
This file contains 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
int* mergesort(int input[], size_t length) | |
{ | |
if(length == 1) | |
{ | |
return input; | |
} | |
int pivot = length/2; | |
size_t a_length = pivot; | |
size_t b_length = length-pivot; | |
int *a = mergesort(input, a_length); | |
int *b = mergesort(input + pivot, b_length); | |
return merge(a, b, a_length, b_length); | |
} | |
int* merge(int left[], int right[], size_t left_length, size_t right_length) | |
{ | |
int i = 0, j = 0, k = 0; | |
int* merged = new int[left_length + right_length]; | |
while(i < left_length && j < right_length) | |
{ | |
if(left[i] < right[j]) { | |
merged[k++] = left[i++]; | |
} else { | |
merged[k++] = right[j++]; | |
} | |
} | |
while(i < left_length) { | |
merged[k++] = left[i++]; | |
} | |
while(j < right_length) { | |
merged[k++] = right[j++]; | |
} | |
return merged; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment