Skip to content

Instantly share code, notes, and snippets.

@rcanepa
Created February 19, 2015 01:35
Show Gist options
  • Save rcanepa/923e04598390a8863033 to your computer and use it in GitHub Desktop.
Save rcanepa/923e04598390a8863033 to your computer and use it in GitHub Desktop.
C++ Merge Sort
#include <iostream>
#include <stdlib.h>
/*
This implementation could be improved using
sentinels.
*/
void merge_sort(int *list, int p, int r);
void merge(int *list, int p, int q, int r);
int main(int argc, char const *argv[])
{
int n = 25;
int list[n];
srand(time(NULL));
std::cout << "Before sorting" << std::endl;
for (int i = 0; i < n; i++)
{
list[i] = rand() % 300;
std::cout << list[i] << ", ";
}
std::cout << std::endl;
merge_sort(list, 0, n - 1);
std::cout << "After sorting" << std::endl;
for (int j = 0; j < n; j++)
{
std::cout << list[j] << ", ";
}
std::cout << std::endl;
return 0;
}
void merge_sort(int *list, int p, int r)
{
if (p < r)
{
int q = (p + r) / 2;
merge_sort(list, p, q);
merge_sort(list, q + 1, r);
merge(list, p, q, r);
}
}
void merge(int *list, int p, int q, int r)
{
int length = r - p + 1;
int i = p, j = p, k = q + 1;
int aux_list[length + p];
std::copy(list, list + length + p , aux_list);
while (j <= q && k <= r)
{
if (aux_list[j] < aux_list[k])
{
list[i] = aux_list[j];
j++;
}
else
{
list[i] = aux_list[k];
k++;
}
i++;
}
while (j <= q)
{
list[i] = aux_list[j];
j++;
i++;
}
while (k <= r)
{
list[i] = aux_list[k];
k++;
i++;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment