选择排序
选择排序算法是通过遍历数组,选择出数组的最小或最大值,与指定位置交换数据,遍历完整个数组的所有位置就完成排序。
n个元素n-1趟,每趟找到尾;O(),不稳定排序。
void SelectSort(int* arr, int size)
{
int i = 0;
for (i = 0; i < size-1; i++)
{
int min = i;
int j = 0;
for (j = i+1; j < size; j++)
{
if (arr[j] < arr[min])
{
min = j;
}
}
Swap(&arr[i], &arr[min]);
}
}
插入排序
插入法排序的思路就是将要排序的数组分两个区间,一个是已排序区间,一个是未排序区间。初始时,默认第一个元素是已排序区间的,后面的所有元素为未排序区间。然后依次取未排序区间的元素,在已排序区间找到合适的位置插入,直到排完所有数据。
n个元素n-1趟,最顺利O(n),最不顺利O(),稳定排序。
void mysort(int *index,int length)
{
int temp;
for(int i = 1;i < length;i++)
{
int j = i - 1;
temp = index[i];
while(index[j] > temp && j >= 0)
{
index[j+1] = index[j];
j--;
}
index[j+1] = temp;
}
}
sort函数
#include <algorithm> //头文件必须有
using namespace std;
一般是sort(数组起点,数组最后一个元素下标+1,比较函数cmp)
比如说:
int arr[3];数组元素下表为0,1,2。排序应为sort(arr,arr+3);
cmp函数可以自己按需求写,不加cmp函数的话默认升序。
练习题
要注意排位,两个同分第三个不同分的话,排名为1 1 3
代码:
#include<iostream>
#include<stdio.h>
#include <cstring>
#include<algorithm>
using namespace std;
struct student {
char id[14];
int score;
int room;
int room_rank;
//int rank;
}stu[30005];
bool cmp(student a, student b) {
if (a.score != b.score) {
return a.score > b.score;
}
else
return strcmp(a.id, b.id) < 0;
}
int main() {
int n;
int count = 0;
cin >> n;
for(int i=1;i<=n;i++) {
int stun;
cin >> stun;
for (int j = 0; j < stun; j++) {
scanf("%s %d", stu[count].id, &stu[count].score);
stu[count].room = i;
count++;
}
sort(stu + count - stun, stu + count, cmp);
stu[count - stun].room_rank = 1;
for (int j = count - stun + 1; j < count; j++) {
if (stu[j].score == stu[j - 1].score) {
stu[j].room_rank = stu[j - 1].room_rank;
}
else {//考场内排名与前人不同分则排名为位次
stu[j].room_rank = j - (count - stun) + 1;
}
}
}
cout << count << endl;
sort(stu, stu + count, cmp);
int rank = 1;
for (int i = 0; i < count; i++) {
if (i > 0 && stu[i].score != stu[i - 1].score) {
rank = i + 1;
}
printf("%s %d %d %d\n", stu[i].id, rank, stu[i].room, stu[i].room_rank);
}
return 0;
}