选择排序
选择排序就是对于一个序列A[0] ~ A{n-1]中,令 i 从头到尾遍历找出这个序列中最小值,并将该值与排序区间[0, n-1]中最前面的值进行交换,那么最前面的值就是整个序列中最小的值
下一步将该区间缩小为[1,n]表明第0个数已经是有序的,以此类推
选择排序时间复杂度为O(n²)
void selectSort()
{
int A[10] = {3,1,4,5,9,2,6,8,7,0};
for(int i = 0; i< 10; i++)
{
int k = i; //假设最前面的值为最小值
for(int j = i; j< 10; j++)
{
if(A[k] > A[j]) k = j;
}
int temp ;
temp = A[k];
A[k] = A[i];
A[i] = temp;
}
for(int i = 0; i< 10;i++)
printf("%d " ,A[i]);
}
插入排序
将未排序序列分成两个部分,第一部分只有一个元素, 第二部分有剩余其他元素,假设第一部分里的内容均有序,将第二部分中最前面的元素插入到第一部分中,比较两个元素大小来确定插入位置,插入时该元素后面的有序元素依次向后移动一个位置,第一部分最后一个元素占掉第二部分第一个元素位置即可,就像排队插队一样,后面的人依次向后动一个位置,当然如果插队插在最后面那么其他人都不用移动位置了
void insertSort()
{
int A[11] = {3,1,4,5,9,2,6,8,7,3,0};
int n = 11;
for(int i = 1; i< n; i++)
{
int temp = A[i];
int j = i;
while(j >0 && A[j-1] > temp)
{
A[j] = A[j-1];
j--;
}
A[j] = temp;
}
for(int i = 0; i< 11;i++)
printf("%d " ,A[i]);
}
C++的Sort函数
对于做题来说,自己写排序太麻烦,C++提供了sort函数进行排序(C有qsort,但是比较麻烦还要用指针)
include<algorithm>
using namespace std;
sort(首元素地址,尾元素地址, 比较函数cmp(非必要))
不写比较函数则默认进行升序排序
void easySort()
{
int A[11] = {3,1,4,5,9,2,6,8,7,3,-2};
sort(A, A+11);
for(int i = 0; i< 11;i++)
printf("%d " ,A[i]);
}
输出结果: -2 1 2 3 3 4 5 6 7 8 9
对double类型进行排序
void easySort()
{
double A[11] = {3.1,1.4,4.5,5.9,9,2,6,8,7,3,-2.3};
sort(A, A+11);
for(int i = 0; i< 11;i++)
printf("%.1f " ,A[i]);
}
输出结果
: -2.3 1.4 2.0 3.0 3.1 4.5 5.9 6.0 7.0 8.0 9.0
对char类型排序(默认为字典序)
void easySort()
{
char A[7] = {'p','r','e','s','e','n','t'};
sort(A, A+7);
for(int i = 0; i< 7;i++)
printf("%c " ,A[i]);
}
输出结果: e e n p r s t
自定义sort函数比较方法
使用sort必须要有可比性,有些数据类型默认情况下不具有可比性,比如传结构体作为参数
这时就要用放到cmp比较函数
int类型降序排序
bool cmp(int a, int b)
{
return a > b;//可以理解为让a在b的前面
}
void easySort()
{
int A[11] = {3,1,4,5,9,2,6,8,7,3,-2};
sort(A, A+7, cmp);
for(int i = 0; i< 11;i++)
printf("%d " ,A[i]);
}
double和char的cmp函数都一样,改一下类型就能用了
结构体排序方法
只对x进行排序
struct node{
int x, y;
}ssd[3];
bool cmp(node a, node b)
{
return a.x > b.x;//可以理解为让a在b的前面
}
void easySort()
{
ssd[0].x = 1;
ssd[0].y = 3;
ssd[1].x = 2;
ssd[1].x = 2;
ssd[2].x = 3;
ssd[2].x = 1;
sort(ssd, ssd+3, cmp);
for(int i = 0; i< 3;i++)
printf("(%d, %d)" ,ssd[i].x, ssd[i].y);
}
>输出结果:(3, 1)(2, 2)(1, 3)
x相等时对y进行排序
struct node{
int x, y;
}ssd[4];
bool cmp(node a, node b)
{
if(a.x != b.x)
return a.x > b.x;//可以理解为让a在b的前面
return a.y > b.y;
}
void easySort()
{
ssd[0].x = 1;
ssd[0].y = 3;
ssd[1].x = 2;
ssd[1].y = 2;
ssd[2].x = 3;
ssd[2].y = 1;
ssd[3].x = 2;
ssd[3].y = 3;
sort(ssd, ssd+4, cmp);
for(int i = 0; i< 4;i++)
printf("(%d, %d)" ,ssd[i].x, ssd[i].y);
}
输出结果:(3, 1)(2, 3)(2, 2)(1, 3)
字符串比较大小
这里比较字符串大小时c语言提供了strcmp函数,而c++的string类重载了< > ==的方法,字符串可以直接比较(C++真香)
bool cmp(string a, string b)
{
return a < b;
}
void easySort()
{
string str[3] = {"abc","bcd", "adb"};
sort(str, str+3, cmp);
for(int i =0; i< 3;i++)
{
cout<< str[i]<<endl;
}
}
cmp比较大小记忆方法
数据从小到大排列:<(小于,最前面的是最小的),就是a<b
数据从大到小排列:>(大于,最前面的是最大的),就是a>b