排序在C++中被整合到了algorithm中,输入sort即可调用,默认为int类型的升序排序,且排序方式Compare可以根据需要自行定义。
下面给出了一个使用样例。
题目:
输入学生的姓名和分数,期待以降序或升序的方式输出学生姓名和分数,当学生分数相同时,期望先录入的同学先输出。
输入:
第一行学生数目n
第二行排序方式(0为降序,1为升序)
后续n行分别为:姓名+空格+分数
输出(n行):
每行的内容分别为:(按指定方式排序后的)姓名+空格+分数
注:
sort默认为int类型的升序
在本题中,由于需要将姓名、成绩、输入次序一并保存,故而封装了结构体Student,需要使用自己定义的Compare函数。
# include# include # include # include using namespace std; struct Student{ string name; int score; int order; }; // increasing, type 1 bool AscendingCompare(Student a, Student b){ if (a.score == b.score){ return a.order < b.order; } else{ return a.score < b.score; } } // decreasing, type 0 bool DescendingCompare(Student a, Student b){ if (a.score == b.score){ return a.order < b.order; } else{ return a.score > b.score; } } int main(){ // total number of student and compare method int number, type; cin >> number >> type; Student arr[number]; // load name, score and order for (int i=0; i cin >> arr[i].name; cin >> arr[i].score; arr[i].order = i; } // compare with appointed method if(type){ sort(arr, arr+number, AscendingCompare); } else{ sort(arr, arr+number, DescendingCompare); } // output for (int i=0;i cout << arr[i].name << " " << arr[i].score << endl; } return 0; }
样例:
查找
上一节中排序的意义之一就是帮助人们更加高效的查找,有序的序列能够加快检索效率而无需逐个元素进行比较,这对在同一序列中多次查找时的意义是十分明显的。
关于查找,我们在此介绍二分查找策略。
// binary search # include# include # include using namespace std; const int MAXN = 100; int arr[MAXN]; bool binarySearch(int len, int target){ int left = 0; int right = len-1; while(left <= right){ int middle = (left + right) / 2; if (arr[middle] < target){ // drop the left half of arr left = middle + 1; } else if (arr[middle] > target){ // drop the right half of arr right = middle - 1; } else{ // find it return true; } } return false; } int main(){ int len; int n; while(scanf("%d", &len) != EOF){ // load data for (int i=0; i cin >> arr[i]; } // sort in Ascending sort(arr, arr+len); // binary search cin >> n; int target; while (n--){ cin >> target; if (binarySearch(len, target)){ printf("Truen"); } else{ printf("Falsen"); } } } return 0; }



