2023.10.6 更新:添加了快速排序详解的内容
C++ 快速排序
通常我们会调用 库函数 #include<algorithm> 直接可以通过一步操作进行快速排序(时间复杂度为
)
1.简单的快速排序
#include<cstdio>
#include<iostream>
using namespace std;
#include<algorithm>
int a[100001],n;
int main()
{
cin>>n;
for(int i=1;i<=n;i++) cin>>a[i]; // 从a[1]开始输入
sort(a+1,a+1+n); //进行快速排序 下标从a[1]开始,一共n个元素排序
for(int i=1;i<=n;i++) printf("%d ",a[i]);
return 0;
}
若下标从0开始输入 则改为
sort(a,a+n); //(数组a 从a[0] 一共 n个元素排序)
2.与结构体有关的排序
首先先按结构体定义数组 (定义成绩 名字)
struct node
{
int cj;
char name;
}a[100001];
然后按照结构体排序
#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm> //sort 函数必须调用的库函数
using namespace std;
struct node
{
int cj;
char na;
}a[100001]; // 定义结构体
int n;
bool cmp(node a,node b) {return a.cj<b.cj;} // 结构体排序 按照结构体内的某个量排序 此排序按照成绩排序
int main()
{
scanf("%d",&n);
for(int i=1;i<=n;i++)
{
scanf("%d",&a[i].cj);
getchar(); // 缓冲区解决掉空格字符的问题
scanf("%c",&a[i].na);
}
sort(a+1,a+1+n,cmp); // 与上述简单快排相同
for(int i=1;i<=n;i++)
printf("%d %c\n",a[i].cj,a[i].na); //输出成绩 和对应的name
return 0;
}
C语言 --- 快速排序
1.简单的快速排序 调用
qsort函数 格式 qsort(s,n+1,sizeof(s[1]),cmp); ---->
qsort(s+1(数组下标从1开始),n+1(数组下标从0开始,到达s[n]为n+1),sizeof(s[1]) (从某个元素开始,cmp(调用比较函数))
关于比较函数写法
int cmp(const void*a,const void *b) // 定义必须 const void*a
{
return *(int *)a>*(int *)b; // 升序 强制转换 成(int *)类型
//return *(int *)a<*(int *)b; 降序
}
qsort函数写法
#include<stdio.h>
#include<stdlib.h>
int n,s[100001];
int cmp(const void *a, const void *b){
return *(int *)a>*(int *)b;//升序 这里与C++相反
// return *(int *)a<*(int *)b;//降序
}
int main()
{
scanf("%d", &n);
for(int i=1;i<=n;i++)
scanf("%d",&s[i]);
qsort(s, n+1, sizeof(s[1]), cmp); //
for(int i=1;i<=n;i++)
printf("%d ",s[i]);
// system("pause");
return 0;
}
2.qsort的结构体排序
cmp 函数里需要定义 struct 的变量 进行比较
int cmp(const void*a,const void *b)
{
struct node *a1=(struct node *)a;
struct node *b1=(struct node *)b;
return (a1->cj)>(b1->cj);
}
qsort结构体排序
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct node{ // 定义struct 结构体
int id,cj;
}s[10001];
int n;
int cmp(const void *a,const void *b) // cmp比较函数
{
struct node *a1=(struct node *)a; // 定义 与强制转换成 (node *)
struct node *b1=(struct node *)b;
//return ((a1->cj)>(b1->cj))?1:-1; 三目运算符
return (a1->cj)>(b1->cj);
} // 相当于 a1.cj>b1.cj;
int main()
{
scanf("%d", &n);
for(int i=1;i<=n;i++)
{
scanf("%d",&s[i].cj);
s[i].id=i;
}
qsort(s, n+1, sizeof(s[1]), cmp); //
for(int i=1;i<=n;i++)
printf("%d %d\n",s[i].cj,s[i].id);
//system("pause");
return 0;
}
总结: C 和 C++ 的快排本质相同 在比较函数cmp中 < > 的答案相反,此外还有C需要运用指针的写法来定义struct
番外篇:快速排序的本质: 转移链接快排详解传送门