Skip to content

Instantly share code, notes, and snippets.

@irchimi
Created June 25, 2020 06:06
Show Gist options
  • Save irchimi/96bdc0f943a4ba2bedc827e25505892f to your computer and use it in GitHub Desktop.
Save irchimi/96bdc0f943a4ba2bedc827e25505892f to your computer and use it in GitHub Desktop.
Example Merge sort in C++
#include <iostream>
void Merge(int arr[], int minIndex, int middleIndex, int maxIndex) {
int left = minIndex;
int right = middleIndex + 1;
int count = maxIndex - minIndex + 1;
int tempArray[100];
int index = 0;
while ((left <= middleIndex) && (right <= maxIndex))
{
if (arr[left] < arr[right])
{
tempArray[index] = arr[left];
left++;
}
else
{
tempArray[index] = arr[right];
right++;
}
index++;
}
for (int i = left; i <= middleIndex; i++)
{
tempArray[index] = arr[i];
index++;
}
for (int i = right; i <= maxIndex; i++)
{
tempArray[index] = arr[i];
index++;
}
for (int i = 0; i < count; i++)
{
arr[minIndex + i] = tempArray[i];
}
}
void MergeSort(int arr[], int minIndex, int maxIndex) {
if (minIndex < maxIndex) {
int middleImdex = (minIndex + maxIndex) / 2;
MergeSort(arr, minIndex, middleImdex);
MergeSort(arr, middleImdex + 1, maxIndex);
Merge(arr, minIndex, middleImdex, maxIndex);
}
}
int main()
{
int mass[5] = {5, 2, 3, 4, 1};
MergeSort(mass, 0, 4);
for (int i = 0; i < 5; i++) {
std::cout << mass[i] << " ";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment