Skip to content

Instantly share code, notes, and snippets.

@kbendick
Created March 8, 2016 19:44
Show Gist options
  • Save kbendick/1de4f311e2a780339eb3 to your computer and use it in GitHub Desktop.
Save kbendick/1de4f311e2a780339eb3 to your computer and use it in GitHub Desktop.
Implementation of merge sort in c++
// Declare/initialize any useful variables here, including the temporary array
// to merge values into and then copy back into the parameter array.
/*
while the temporary array is not filled
if there are no more values in the left part of a,
move next value from right part of a into next index of the temporary array otherwise, if there are no more values in the right part of a,
move next value from left part of a into next index of the temporary array otherwise (values in each part) compare the first value in each part
move smallest value from a into next index of the temporary array
Copy all values from the temporary array back into a, starting at left_low
*/
void merge_sort(int a[], int length) {
merge_sort(a, 0, length-1);
}
void merge_sort(int a[], int low, int high) {
if (low >= high) //Base case: 1 value to sort->sorted
return; //(0 possible only on initial call)
else {
int mid = (low + high)/2; //Approximate midpoint*
merge_sort(a, low, mid); //Sort low to mid part of array
merge_sort(a, mid+1, high); //Sort mid+1 to high part of array
merge(a, low, mid, mid+1,high); //Merge sorted subparts of array
}
}
void merge(int a[], int left_low, int left_high, int right_low, int right_high)
{
int length = right_high-left_low+1;
int temp[length];
int left = left_low;
int right = right_low;
for (int i = 0; i < length; ++i) {
if (left > left_high)
temp[i] = a[right++];
else if (right > right_high)
temp[i] = a[left++];
else if (a[left] <= a[right])
temp[i] = a[left++];
else
temp[i] = a[right++];
}
for (int i=0; i< length; ++i)
a[left_low++] = temp[i];
}
@LionRoar
Copy link

LionRoar commented Oct 5, 2017

very efficient 👍 but there minor observation in Merge() function you cant just declare an array on int with variable int temp[length];
i think you should invoke it in the heap then delete it at the end should be like int* temp = new int [length];
then at the end of the function
delete temp;
thank you the code is very elegant and very helpful with all those comments 💯

@RyanGFerguson
Copy link

very efficient but there minor observation in Merge() function you cant just declare an array on int with variable int temp[length];
i think you should invoke it in the heap then delete it at the end should be like int* temp = new int [length];
then at the end of the function
delete temp;

Don't forget the brackets on your delete
delete[] temp;

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