Last active
August 9, 2023 08:27
-
-
Save christophewang/1f2da2e44b03778f2f9f to your computer and use it in GitHub Desktop.
Merge Sort in 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
#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); | |
} |
tried to run your code it can't run. new to cpp though
probeer dit :)
https://gist.github.com/KotoRina/96bdc0f943a4ba2bedc827e25505892f
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
tried to run your code it can't run. new to cpp though