The so-called stable sort, refers to the order of a sequence, if the value of two elements is equal, then the original chaos in the previous element is now (after the order) is still in front. The Stable_sort () function is provided in the STL to allow us to sort stably. To better illustrate the effect of stable sorting, we define a struct element, a value member, and an index member that represents the value of the element, which represents the index at the time of the order.
Stable_sort () is implemented internally by merge sort.
Coded by code Madman
//http://www.programlife.net/
#include <iostream>
#include <vector>
# Include <algorithm>
#include <iterator>
using namespace std;
typedef struct TAGNODE
{
int value;
int index;
} Node;
BOOL MYCMP (const node& A, const node& b)
{
return a.value < B.value;
}
int main (int argc, char **argv)
{
vector<node> coll;
Node tmp;
int idx = 0, num;
while (CIN >> num && num)
{
++idx;
Tmp.value = num;
Tmp.index = idx;
Coll.push_back (TMP);
}
Stable_sort (Coll.begin (), Coll.end (), mycmp);
cout << "Index\tvalue:" << Endl;
Vector<node>::iterator Pos;
for (pos = Coll.begin (); pos! = Coll.end (); ++pos)
{
cout << pos->index << "\ t" << pos->v Alue << Endl;
}
return 0;
}
The running result of the program is as shown in the figure below, as you can see, for elements with the same element value, the index is small in front, and the stable sort is such an effect.