稳定排序
#include <iostream>
#include <vector>//STL容器
#include <algorithm>
#include <string>
using namespace std;
struct List//由于多种不同类型的数组,所以用结构体
{
int num;
string name;
int score;
};
bool comp(List xx, List yy)//bool类型只有两个值,0和1;成绩不相等则按照成绩从高到低排。
{
return (xx.score != yy.score) ? (xx.score > yy.score):(xx.num < yy.num);
}
int main()
{
int notStable, error;
vector<List> a,b;//建立两个新的不定数列a,b;注意数组的元素时结构体。具体情况具体使用
int n;
while (cin >> n)
{
List temp;//定义了一个结构体变量
for (int i = 0; i < n; i++)//每次读入把一组数据读入
{
temp.num = i;//结构体中此作用是给表上序号,好按照顺序排列。
cin >> temp.name; cin >> temp.score;
a.push_back(temp);
}
for (int i = 0; i < n; i++)//存储原来的排列
{
temp.num = i;
cin >> temp.name; cin >> temp.score;
b.push_back(temp);
}
sort(a.begin(), a.end(), comp);//对a进行排序,成绩从高到低,否则相等则按照顺序
notStable = 0, error = 0;//相当于一个flag;
for (int i = 0; i < n; i++)
{
if (a[i].score != b[i].score) error = 1;//成绩不相等
if (a[i].name != b[i].name) notStable = 1;//没名字按照顺序输出。
}
if (error == 1)
{
cout << "Error" << endl;
for (int i = 0; i < n; i++)//一个for循环,将名字和分数输出。
cout << a[i].name << " " << a[i].score << endl;
}
else if (error == 0 && notStable == 1)
{
cout << "Not Stable" << endl;
for (int i = 0; i < n; i++)
cout << a[i].name << " " << a[i].score << endl;
}
else
{
cout <<"Right"<< endl;
}
a.clear(); b.clear();//要把数据清空,多组数据输入。
}
}