Skip to content

Instantly share code, notes, and snippets.

@christophewang
Last active August 9, 2023 08:27
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save christophewang/1f2da2e44b03778f2f9f to your computer and use it in GitHub Desktop.
Save christophewang/1f2da2e44b03778f2f9f to your computer and use it in GitHub Desktop.
Merge Sort in C++
#include <iostream>
void printArray(int *array, int n)
{
for (int i = 0; i < n; ++i)
std::cout << array[i] << std::endl;
}
void merge(int *array, int low, int mid, int high)
{
int temp[high + 1];
int i = low;
int j = mid + 1;
int k = 0;
while (i <= mid && j <= high)
{
if (array[i] <= array[j])
temp[k++] = array[i++];
else
temp[k++] = array[j++];
}
while (i <= mid)
temp[k++] = array[i++];
while (j <= high)
temp[k++] = array[j++];
k--;
while (k >= 0)
{
array[k + low] = temp[k];
k--;
}
}
void mergeSort(int *array, int low, int high)
{
int mid;
if (low < high)
{
mid = (low + high) / 2;
mergeSort(array, low, mid);
mergeSort(array, mid + 1, high);
merge(array, low, mid, high);
}
}
int main()
{
int array[] = {95, 45, 48, 98, 1, 485, 65, 478, 1, 2325};
int n = sizeof(array)/sizeof(array[0]);
std::cout << "Before Merge Sort :" << std::endl;
printArray(array, n);
mergeSort(array, 0, n - 1);
std::cout << "After Merge Sort :" << std::endl;
printArray(array, n);
return (0);
}
@BlackHawk0
Copy link

tried to run your code it can't run. new to cpp though

@irchimi
Copy link

irchimi commented Jun 25, 2020

tried to run your code it can't run. new to cpp though

probeer dit :)
https://gist.github.com/KotoRina/96bdc0f943a4ba2bedc827e25505892f

@Mudassir742
Copy link

In cpp you cannot use temp[high+1], you have to create dynamic array like int *temp=new int[high+1] and at the end of merge function delete this temp by using this statement delete[]temp.

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