From cppreference, I know that for stable_sort
:
The order of equal elements is guaranteed to be preserved.
I also read this question What is stability in sorting algorithms and why is it important? and understand the concept and basic usage of stability.
Here's how I understand stable sort:
Let's say I have unordered flight departure time and destination.
First, I sort it by time. It would be like
d-time dest
1 A
2 B
3 C
4 A
5 B
Then stable sort by dest. It would be like
dest d-time
A 1 (stable sort guarantee that [A,1] comes before [A,4])
A 4
B 2 (stable sort guarantee that [B,2] comes before [B,5])
B 5
C 3
But an example C++ Primer seems to indicate that stable_sort
also guarantee the order of previous unequal elements (if so, it means stable_sort
keeps all the original order).
Sample code:
#include <iostream>
#include <sstream>
#include <vector>
#include <algorithm>
using namespace std;
bool isShorter(const string &s1, const string &s2)
{
return s1.size() < s2.size();
}
int main(int args, char *argv[])
{
vector<string> words;
string in_word;
istringstream isin("the quick red fox jumps over slow turtles");
while (isin >> in_word) {
words.push_back(in_word);
}
sort(words.begin(), words.end());
auto end_unique = unique(words.begin(), words.end());
words.erase(end_unique, words.end());
stable_sort(words.begin(), words.end(), isShorter);
for (auto &s : words) {
cout << s << " ";
}
cout << endl;
}
Here's the text makes me question that whether stable_sort
keeps all the original elements' order.
Assuming
words
was in alphabetical order before this call (the first sorting and erasing function calls), after the call,words
will be sorted by element size, and the words of each length remain in alphabetical order. If we run this code on our original vector, the output will be
fox red the over slow jumps quick turtle
After first sorting and erasing, I have:
fox jumps over quick red slow the turtles
After stable sort, I have:
fox red the over slow jumps quick turtle
So my question is:
For stable_sort
, just see the first 3 elements:
fox red the
, is this order fixed? Or it's just one possible order among the arrangements:
fox red the
fox the red
the red fox
the fox red
... (6 results)
I mean, the document only said stable_sort
keeps the original order of equal elements. fox red the
are not equal. They have order. But from the quoted text and output, it seems to indicate that It simply keeps all the original order.
Do I misunderstand something or the textbook is wrong here and the output is just happened to follow the previous sorting order?