标签:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
#include
<stdio.h> #define
N 10 int main() { int a[N]
= {3,5,2,9,7,4,8,1,0,6}, i, j, t; for (i
= 0; i < N-1; i++) { //共进行N-1趟 for (j
= 0; j < N–i-1; j++) /*已排好的数据不参与比较
*/ if (a[j]
> a[j+1]) {
t
= a[j];
a[j] = a[j+1];
a[j+1] = t; } } for (i
= 0; i <= N-1; i++) printf (“%3d”,
a[i]); printf (“\n”); getch(); return 0; } |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
#include
<stdio.h> #define
N 10 int main() { int a[N]
= {3,5,2,9,7,4,8,1,0,6}, i, j, min, t; for (i
= 0; i < N-1; i++) {
//共进行N-1趟 /*
首先将最前面数当作擂主,记录其序号 */
min =
i; //当进行第i趟时,最前面数的序号是i /*
后面的每一个数都与擂主进行比较,以便找出最小数 */ for (j
= i+1; j <= N-1; j++) if (a[j]
< a[k]) //擂主是a[k],未必总是a[i]
min
= j; //若比擂主还小,则记录其序号 /*
将最小数交换到(剩下数的)最前面 */ if(min!=i){
t
= a[k]; a[k]
= a[i]; a[i]
= t; }
} for (i
= 0; i <= N-1; i++) printf (“%3d”,
a[i] ); printf (“\n”); getch(); return 0; } |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
#define
N 10 #include
<stdio.h> int main() { int a[N]
= {3,5,2,9,7,4,8,1,0,6}, i, j, t; for (i
= 1; i <= N-1; i++) { t
= a[i]; //保存a[i],因a[i]会被覆盖 for (j
= i-1; a[j]>t && j>=0; j--) //
a[j]>t不能写成a[j]> a[i] a[j+1]
= a[j]; a[j+1]
= t; } for (i
= 0; i <= N-1; i++) printf (“%3d”,
a[i] ); printf (“\n”); getch(); return 0; } |
1)稳定2)空间代价:Θ(1)3)时间代价:插入每个记录需要Θ(log i)比较,最多移动i+1次,最少2次最佳情况Θ(nlog n),最差和平均情况Θ(n^2)。
标签:
原文地址:http://blog.csdn.net/luopingfeng/article/details/44260423