成绩排序习题
題目描述查找和排序題目:輸入任意(用戶,成績)序列,可以獲得成績從高到低或從低到高的排列,相同成績
都按先錄入排列在前的規則處理。示例:
jack 70
peter 96
Tom 70
smith 67
從高到低 成績
peter 96
jack 70
Tom 70
smith 67
從低到高
smith 67
jack 70
Tom 70
peter 96
輸入描述:
輸入多行,先輸入要排序的人的個數,然后輸入排序方法0(降序)或者1(升序)再分別輸入他們的名字和成績,以一個空格隔開
輸出描述:
按照指定方式輸出名字和成績,名字和成績之間以一個空格隔開
示例:(輸入如下)
3
0
fang 90
yang 50
ning 70
輸出為:
fang 90
ning 70
yang 50
在這采用直接插入排序,當然別的排序方法也是可以的,但必須是穩定的。
#include<iostream> typedef struct{char* a;int b;}type; int main() {using namespace std;int index1, index2;while(cin >> index1 >> index2)//為方便測試多個用例{type* ele = new type[index1];int i;for (i = 0; i < index1; i++){ele[i].a = new char[30];cin >> ele[i].a >> ele[i].b;}//輸入完所有數據保存在ele結構體數組當中。type temp;int j;temp.a = new char[30];if (index2 == 1)//直接插入排序(升序){for (i = 1; i < index1; i++){if (ele[i].b < ele[i - 1].b){temp.a = ele[i].a;temp.b = ele[i].b;for (j = i - 1; temp.b < ele[j].b&&j >= 0; j--){ele[j + 1].a = ele[j].a;ele[j + 1].b = ele[j].b;}ele[j + 1].a = temp.a;ele[j + 1].b = temp.b;}}for (i = 0; i < index1; i++)cout << ele[i].a << ' ' << ele[i].b << endl;}else//直接插入排序(降序){for (i = 1; i < index1; i++){if (ele[i].b > ele[i - 1].b){temp.a = ele[i].a;temp.b = ele[i].b;for (j = i - 1; temp.b > ele[j].b&&j >= 0; j--){ele[j + 1].a = ele[j].a;ele[j + 1].b = ele[j].b;}ele[j + 1].a = temp.a;ele[j + 1].b = temp.b;}}for (i = 0; i < index1; i++)cout << ele[i].a << ' ' << ele[i].b << endl;}delete[]ele;}return 0; }總結
- 上一篇: 插入排序之——直接插入排序(c/c++)
- 下一篇: 插入排序之——二分(折半)插入排序(c/