1.冒泡排序
1.1算法
冒泡排序(buddle-sort)算法的运作如下:(从后往前)
比较相邻的元素。如果第一个比第二个大,就交换他们两个。
对每一对相邻元素作同样的工作,从开始第一对到结尾的最后一对。在这一点,最后的元素应该会是最大的数。
针对所有的元素重复以上的步骤,除了最后一个。
持续每次对越来越少的元素重复上面的步骤,直到没有任何一对数字需要比较。
1.2 实现
?
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
|
//
// main.c
// BubbleSort
//
// Created by Wuyixin on 2017/6/2.
// Copyright © 2017年 Coding365. All rights reserved.
//
#include <stdio.h>
void bubbleSort(int a[],int n){
int i,j;
for (i = 0; i < n - 1; i++) {
for (j = 0; j < n - i; j++) {
if (a[j] > a[j + 1]){
int temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
}
}
}
}
int main(int argc, const char * argv[]) {
int a[] = {9,3,1,4,7,6,5,8,2};
bubbleSort(a, 9);
int i = 0;
while (i < 9)
printf("%d ",a[i++]);
return 0;
}
|
2.选择排序
2.1 算法
选择排序(selection-sort)是一种简单直观的排序算法。它的工作原理是每一次从待排序的数据元素中选出最小(或最大)的一个元素,存放在序列的起始位置,直到全部待排序的数据元素排完
2.2实现
?
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
|
//
// main.c
// SelectionSort
//
// Created by Wuyixin on 2017/6/2.
// Copyright © 2017年 Coding365. All rights reserved.
//
#include <stdio.h>
void selectionSort(int a[],int n){
int i,j,min,temp;
for (i = 0; i < n; i++) {
min = i;
for (j = i + 1; j < n; j++) {
if (a[j] < a[min])
min = j;
}
if (i != min){
temp = a[i];
a[i] = a[min];
a[min] = temp;
}
}
}
int main(int argc, const char * argv[]) {
int a[] = {9,3,1,4,7,6,5,8,2};
selectionSort(a, 9);
int i = 0;
while (i < 9)
printf("%d ",a[i++]);
return 0;
}
|
3.插入排序
3.1 算法
插入排序(insertion-sort)的基本思想是:每步将一个待排序的纪录,按其关键码值的大小插入前面已经排序的文件中适当位置上,直到全部插入完为止。
3.2 实现
?
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
//
// main.c
// InsertionSort
//
// Created by Wuyixin on 2017/6/2.
// Copyright © 2017年 Coding365. All rights reserved.
//
#include <stdio.h>
void insertionSort(int a[],int n){
int i,j,temp;
for (i = 1; i < n ; i++) {
temp = a[i];
for (j = i; j > 0 && temp < a[j - 1]; j--) {
a[j] = a[j - 1];
}
a[j] = temp;
}
}
int main(int argc, const char * argv[]) {
int a[] = {9,3,1,4,7,6,5,8,2};
insertionSort(a, 9);
int i = 0;
while (i < 9)
printf("%d ",a[i++]);
return 0;
}
|
相关文章
猜你喜欢
- 个人网站搭建:如何挑选具有弹性扩展能力的服务器? 2025-06-10
- 个人服务器网站搭建:如何选择适合自己的建站程序或框架? 2025-06-10
- 64M VPS建站:能否支持高流量网站运行? 2025-06-10
- 64M VPS建站:怎样选择合适的域名和SSL证书? 2025-06-10
- 64M VPS建站:怎样优化以提高网站加载速度? 2025-06-10
TA的动态
- 2025-07-10 怎样使用阿里云的安全工具进行服务器漏洞扫描和修复?
- 2025-07-10 怎样使用命令行工具优化Linux云服务器的Ping性能?
- 2025-07-10 怎样使用Xshell连接华为云服务器,实现高效远程管理?
- 2025-07-10 怎样利用云服务器D盘搭建稳定、高效的网站托管环境?
- 2025-07-10 怎样使用阿里云的安全组功能来增强服务器防火墙的安全性?
快网idc优惠网
QQ交流群
您的支持,是我们最大的动力!
热门文章
-
系统监控中心:一个理想的 Linux 任务管理器和资源监视器
2025-05-25 31 -
2025-06-04 54
-
2025-05-27 46
-
2025-05-29 86
-
2025-06-04 37
热门评论

