STL Stable_sort Stable Sequencing

Source: Internet
Author: User
Tags sort

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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.