当前位置:网站首页>C语言实现八种排序(2)
C语言实现八种排序(2)
2022-06-11 21:36:00 【爱学代码的学生】
2. 交换排序
2.1 冒泡排序
什么是冒泡排序?
冒泡排序(Bubble Sort)也是一种简单直观的排序算法。
它重复地走访过要排序的数列,一次比较两个元素,如果他们的顺序错误就把他们交换过来。走访数列的工作是重复地进行直到没有再需要交换,也就是说该数列已经排序完成。
这个算法的名字由来是因为越小的元素会经由交换慢慢“浮”到数列的顶端。
代码实现如下:
void BubbleSort(int *a,int length){
int i,j;
int flag=1; //判断是否进行循环
for(i=0;i<length-1&&flag==1;i++){
for(j=0;j<length-1-i;j++){
flag=0;
if(a[j]>a[j+1]){
flag=1;
int temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
}但由于冒泡排序的时间复杂度过高,所有引申出了一种新型的排序 -- 快速排序(QuickSort)。
这个名字就能彰显出其速率之快.
那这种排序是如何实现的?
代码如下:
//快速排序
int Partition(int*a,int left,int right){
int temp=a[left];//left下标作为基准数
while(left<right){
while(left<right&&a[right]>temp){
right--;
}
if(left<right){
a[left]=a[right];
}
while(left<right&&a[left]<temp){
left++;
}
if(left<right){
a[right]=a[left];
}
}
a[right]=temp;
return right;
}
void QuickSort(int*a,int left,int right){
if(left<right){
int pivot=Partition(a,left,right);
QuickSort(a,left,pivot-1);
QuickSort(a,pivot+1,right);
}
}我们首先选择一个作为基准数,然后遍历整个数组(除了基准数),将小于基准数的放在它的左边,大于基准数的放在它的右边。
然后将基准数的左边和右边右看成一个数组,重复上述操作,直到每个数组只剩一个元素。

让我再水一期
边栏推荐
- Using the sap ui5 cli command line tool to build and run SAP ui5 applications
- 网络连接正常但百度网页打不开显示无法访问此网站解决方案
- LeetCode-155-最小栈
- How to manually send events exposed by SAP commerce cloud mock application using SAP kyma console
- LabVIEW Arduino electronic weighing system (project Part-1)
- Flink error: multiple tasks are started, and only one task is executed
- 实验10 Bezier曲线生成-实验提高-交互式生成B样条曲线
- Software test plan
- LeetCode-76-最小覆盖子串
- 如何创建最简单的 SAP Kyma Function
猜你喜欢

A collection of commonly used open source data sets for face recognition

RPA丨首席财务官如何找到数字化转型“超级入口”?

Leetcode-98- validate binary search tree

Leetcode-129- sum of numbers from root node to leaf node

如何查看win系统的安装日期

多态的所有特征

Only 38 years old! Zhou Chuan, a researcher of the Chinese Academy of Sciences, died unfortunately. Rao Yi sent a document to mourn: he guided me when he was still my student

LabVIEW控制Arduino实现红外测距(进阶篇—6)
![[Part 15] use and basic principle of forkjoinpool [key]](/img/36/e21b16ec92d444149bc793f340f9f3.jpg)
[Part 15] use and basic principle of forkjoinpool [key]

类和对象(1)
随机推荐
RPA+低代码为何是加速财务数字化转型之利器?
LeetCode-155-最小栈
如何使用事物码 SAT 查找某个 SAPGUI 屏幕字段对应的后台存储数据库表的名称试读版
线性表的链式存储结构
如何利用RPA机器人开启货代行业数字化转型第一步?
「大模型」之所短,「知识图谱」之所长
Hangzhou Electric Zhongchao 91006 guess the weight
A collection of commonly used open source data sets for face recognition
Some error reporting assemblies of cann code
How does the chief financial officer of RPA find the "super entrance" of digital transformation?
JVM | virtual machine stack (local variable table; operand stack; dynamic link; method binding mechanism; method call; method return address)
实验10 Bezier曲线生成-实验提高-交互式生成B样条曲线
Diary at 16:29:41 on June 9, 2022
8、 BOM - chapter after class exercises and answers
Building a custom CNN model: identifying covid-19
一步步把 SAP UI5 应用部署到 SAP BTP Kyma 运行环境中去
apache 本地多端口配置
AC automata
ESP32C3 Arduino库使用方法
CANN编码的一些报错汇编