Merge sort is a "devide-and-conquer" algorithm. The idea is based on the fact that some problems (including sorting) become easier when they are applied to shorter sequences.
Suppose you have two sorted sequences, how do you "merge" them into one sorted sequence?
All you have to do now is to create "short" sorted sequences. A sequence of one element is always sorted. So, basically, what you do is:
- Divide (...until every part is sorted)
- Merge (every sorted piece into a larger piece)
This is usually done recursively:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
|
mergesort(sequence s)
{
if(size > 1)
{
mergesort(s.first_half);
mergesort(s.second_half);
merge(s.first_half /*which is now sorted*/, s.second_half /*which is also sorted*/);
}
/* else: s is sorted... */
}
merge(sequence s1, sequence s2)
{
//... you know what to do here...
}
|
I have posted vague pseudocode, because I think that if you want to understand the algorithm, you should implement (and think about it) yourself. If you just want a copy&paste solution, use std::stable_sort instead.
Edit:
Argh, wrote "mergesort" in the declaration and "sort" in the body. Of course, it should be recursive...