两种排序算法
#include <stdio.h>
//选择排序
void selectSort(int b[]){
for(int i = 0;i<10;i++){
int k = i;
for(int j = i;j<10;j++){ //i~10中选出最小的,下标是k
if(b[j]<b[k]){
k=j; //较小的是k
}
}
int temp = b[i]; //最小的交换到待排序列最前
b[i] = b[k];
b[k] = temp;
}
}
//插入排序
void insertSort(int b[]){
for(int i=1;i<10;i++){ //从第二个开始,与前面的每个比较,并插入适当位置
int temp = b[i],j=i; //参与比较的元素给temp
while(j>0 && temp<b[j-1]){ //与前面的元素比较,小于则交换
b[j] = b[j-1];
j--;
}
b[j]=temp;
}
}
//给一个数组
int main(){
int a[10]={
4,6,2,9,5,1,7,3,6,2
};
selectSort(a); //调用函数
insertSort(a);
for(int i=0;i<10;i++){
printf("%d",a[i]);
}
}
sort( )函数用法
只需要排序结果时,可调用c++的sort( )函数
//利用sort()函数排序
#include <stdio.h>
#include <algorithm>
using namespace std;
//sort(首元素地址,尾元素地址的下一个地址,*比较函数) ;默认递增
int main(){
int a[6]={
9,4,2,5,6,-1
};
//将a[0]~a[3]从小到大排列
sort(a,a+4);
for(int i=0;i<6;i++){
printf("%d ",a[i]);
}
printf("\n");
//将a[0]~a[5]从小到大排序
sort(a,a+6);
for(int i = 0;i<6;i++){
printf("%d ",a[i]);
}
return 0;
}
double型数组:
//type:double
#include <stdio.h>
#include <algorithm>
using namespace std;
int main(){
double a[]={
1.1,5,-3.141
};
sort(a,a+3);
for(int i=0;i<3;i++){
printf("%.3lf ",a[i]);
}
return 0;
}
char型数组:
//type:char
#include <stdio.h>
#include <algorithm>
using namespace std;
int main(){
char c[] = {
'l','w','a','x'
};
sort(c,c+4);
for(int i = 0;i<4;i++){
printf("%c ",c[i]);
}
return 0;
}
sort中的cmp函数
其中,sort()的第三个参数compare函数,实现比较的规则,默认为升序,double、char同理
//从大到小排序
#include <stdio.h>
#include <algorithm>
using namespace std;
bool cmp(int a,int b){ //写一个比较大小的函数
return a>b;
}
int main(){
int a[]={
3,1,4,2
};
sort(a,a+4,cmp); //sort中使用了这个函数
for(int i = 0;i<4;i++){
printf("%d ",a[i]);
}
return 0;
}
结构体数组的排序
结构体数组按x从大到小排序
//结构体数组的排序
#include <stdio.h>
#include <algorithm>
using namespace std;
//定义如下结构体:
struct node{
int x,y;
} ssd[10];
//将ssd数组按照x从大到小排序:
bool cmp(node a,node b){
return a.x>b.x;
}
int main(){
ssd[0].x=2; //{2,6}
ssd[0].y=6;
ssd[1].x=8; //{8,1}
ssd[1].y=1;
ssd[2].x=1; //{1,3}
ssd[2].y=3;
sort(ssd,ssd+3,cmp);
for(int i = 0;i < 3;i ++){
printf("%d %d\n",ssd[i].x,ssd[i].y);
}
return 0;
}
若对x和y都按一定规则排序:
//结构体数组的排序
#include <stdio.h>
#include <algorithm>
using namespace std;
struct node{
int x,y;
} ssd[10];
//将ssd数组按照x从大到小排序,x相等情况下,按照y的大小从小到大排序
bool cmp(node a,node b){
if(a.x!=b.x) return a.x>b.x;
else return a.y<b.y;
}
int main(){
ssd[0].x=2; //{2,6}
ssd[0].y=6;
ssd[1].x=8; //{8,8}
ssd[1].y=8;
ssd[2].x=2; //{2,3}
ssd[2].y=3;
sort(ssd,ssd+3,cmp);
for(int i = 0;i < 3;i ++){
printf("%d %d\n",ssd[i].x,ssd[i].y);
}
return 0;
}
排名中sort函数的应用
struct Student{
char name[10]; //姓名
char id[10]; //准考证号
int score; //分数
int r; //排名
} stu[100010];
//对所有学生按成绩从高到低排序,分数相同的按姓名的字典序从小到大排序
bool cmp(Student a,Student b){
if(a.score!=b.score)
return a.score>b.score;
/* strcmp(str1,str2)函数用于比较两个char型数组的字典序大小;
当str1的字典序小于str2时,返回一个负数;
当str1的字典序等于str2时,返回0;
当str1的字典序大于str2时,返回一个正数 */
else
return strcmp(a.name,b.name)<0; //返回负数,但不能直接写==-1,因返回值与编译器有关
}