当前位置:网站首页>C语言——冒泡排序
C语言——冒泡排序
2022-07-17 05:10:00 【numb and dying】
一、问题的描述
冒泡排序(Bubble Sort),是一种计算机科学领域的较简单的排序算法。
它重复地走访过要排序的元素列,依次比较两个相邻的元素,如果顺序(如从大到小、首字母从Z到A)错误就把他们交换过来。走访元素的工作是重复地进行,直到没有相邻元素需要交换,也就是说该元素列已经排序完成。
这个算法的名字由来是因为越小的元素会经由交换慢慢“浮”到数列的顶端(升序或降序排列),就如同碳酸饮料的气泡最终会上浮到顶端一样,故名“冒泡排序”。
二、算法原理
比较相邻的元素。如果第一个比第二个大,就交换他们两个。
对每一对相邻元素做同样的工作,从开始第一对到结尾的最后一对。在这一点,最后的元素应该会是最大的数。
针对所有的元素重复以上的步骤,除了最后一个。
持续每次对越来越少的元素重复上面的步骤,直到没有任何一对数字需要比较。
三、算法实现
#include <stdio.h>
void Bubble_Sort(int arr[], int n) {
int flag = 1;
for (int i = 0; i < n - 1; i++) {
flag = 1;
for (int j = 0; j < n - 1 - i; j++) {
if (arr[j] > arr[j + 1]) {
int tmp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = tmp;
flag = 0;
}
}
if (flag == 1) {
break;
}
}
}
int main() {
int arr[30] = {0};
int n = 0;
printf("请输入数组的大小:\n");
scanf("%d", &n);
printf("依次输入各个元素:\n");
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
printf("\n原数组:");
for (int i = 0; i < n; i++) {
if (i == (n - 1)) {
printf("%d\n", arr[i]);
break;
}
printf("%d, ", arr[i]);
}
Bubble_Sort(arr, n);
printf("\n排序后数组:");
for (int i = 0; i < n; i++) {
if (i == (n - 1)) {
printf("%d\n", arr[i]);
break;
}
printf("%d, ", arr[i]);
}
return 0;
}四、算法测试

五、算法稳定性
冒泡排序就是把小的元素往前调或者把大的元素往后调。比较是相邻的两个元素比较,交换也发生在这两个元素之间。所以,如果两个元素相等,是不会再交换的;如果两个相等的元素没有相邻,那么即使通过前面的两两交换把两个相邻起来,这时候也不会交换,所以相同元素的前后顺序并没有改变,所以冒泡排序是一种稳定的排序算法。
边栏推荐
- MySQL queries the data of the current day, this week, this month and last month
- 关于AS安装之后的一些细碎事项
- Bottomsheetdialogfragment imitation Tiktok comment box
- idea导入本地包
- Page navigation of wechat applet
- Table field attribute query
- 回顾我的第一份工作求职之旅
- Syntax differences between PgSQL and Oracle (SQL migration records)
- 4.东软跨境电商数仓项目--数据采集通道搭建之用户行为数据采集通道搭建(2022.6.1-2022.6.4)
- Calculator of wechat applet
猜你喜欢

1. Neusoft cross border e-commerce warehouse demand specification document

cuda11.0的pytorch安装小计

4. Neusoft cross border e-commerce data warehouse project - user behavior data acquisition channel construction of data acquisition channel construction (2022.6.1-2022.6.4)

MySQL learning notes (4) - (basic crud) operate the data of tables in the database

微信小程序的页面导航

Macro definition of C language

LiveData浅析

Spark core programming (4) -- spark operation architecture

5.1 business data acquisition channel construction of data acquisition channel construction

JNA加载DLL及在jar中的运用
随机推荐
对象转map
SQL练习题集合
Judging prime
replace限制文本框只能输入数字,数字和字母等的正则表达式
typedef
class文件格式的理解
Paddle的OCR标签转化为TXT格式
微信小程序的页面导航
1.東軟跨境電商數倉需求規格說明文檔
Functions and parameters
SnackBar源码解析及封装
微信小程序代码的构成
Minor problems of GCC compiling C language in ubantu
SnackBar source code analysis and packaging
10.数据仓库搭建之DWD层搭建
Scala primary practice - statistics of mobile phone traffic consumption (1)
1.东软跨境电商数仓需求规格说明文档
Regular replace group (n) content
微信小程序的自定义组件
2021-05-21