Skip to content

Instantly share code, notes, and snippets.

@hobelinm
Created March 9, 2014 06:16
Show Gist options
  • Save hobelinm/9443595 to your computer and use it in GitHub Desktop.
Save hobelinm/9443595 to your computer and use it in GitHub Desktop.
Simple implementation of Merge Sort Algorithm in C++
// Fill a random vector
template <typename Comparable>
void fillRandom(vector<Comparable> &iArray, Comparable range)
{
srand((unsigned)time(0));
for(Comparable i = 0; i < iArray.size(); i++)
{
iArray[i] = rand() % range;
}
}
/**********************************************************************
MERGE SORT:
- Recurse over first half
- Recurse over second half
- Merge by getting biggest elements from two data sets
**********************************************************************/
template <typename Comparable>
void mergeSort(vector<Comparable> &a, int first, int last)
{
if(first < last)
{
int mid = (first + last) / 2;
mergeSort(a, first, mid);
mergeSort(a, mid + 1, last);
merge(a, first, mid, last);
}
}
template <typename Comparable>
void merge(vector<Comparable> &a, int first, int mid, int last)
{
vector<Comparable>tmp(last - first + 1);
int index1 = first;
int index2 = mid + 1;
int index = 0;
// As long as both lists still have elements, add the next
while(((index1 <= mid) || (index2 <= last)) && (index < (last - first + 1)))
{
if((index1 <= mid) && (index2 <= last))
{
tmp[index] = (a[index1] < a[index2])? a[index1] : a[index2];
(a[index1] < a[index2])? index1++ : index2++;
}
else if(index1 > mid)
{
tmp[index] = a[index2];
index2++;
}
else // index2 > last
{
tmp[index] = a[index1];
index1++;
}
index++;
}
for(int i = 0; i < last - first + 1; i++)
{
a[first + i] = tmp[i];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment