插入排序(Windows+VC6.0環(huán)境編譯)
插入排序:每次將一個待排序的數(shù)據(jù)元素,插入到前面已經排好序的數(shù)列中的適當位置,使數(shù)列依然有序;直到待排序數(shù)據(jù)元素全部插入完為止。時間復雜度:O(n的平方)
1
#include <stdio.h>
2
#include <cstdlib>
3
4
#define TOTAL_NUM 1000
5
#define MAX_NUM 100
6
7
int main(int argc,char* argv[])
8

{
9
int Sort[TOTAL_NUM];
10
11
int iPrintCount = 0;
12
int i = 0;
13
printf("::: old order ::: \n");
14
for (i=0;i<TOTAL_NUM;i++)
15
{
16
Sort[i] = (rand()+MAX_NUM)%MAX_NUM;
17
printf("%5ld ",Sort[i]);
18
if(++iPrintCount==10)
19
{
20
iPrintCount = 0;
21
printf("\n");
22
}
23
}
24
25
for (i=0;i<TOTAL_NUM;i++)
26
{
27
int iVal = Sort[i];
28
if (iVal<Sort[0])
29
{
30
for(int k=i;k>0;k--)
31
Sort[k] = Sort[k-1];
32
Sort[0] = iVal;
33
}else
34
{
35
for (int j=0;j<i;j++)
36
{
37
if (iVal>=Sort[j] && iVal<Sort[j+1])
38
{
39
for(int k=i;k>j+1;k--)
40
Sort[k] = Sort[k-1];
41
Sort[j+1] = iVal;
42
break;
43
}
44
}
45
}
46
}
47
48
iPrintCount = 0;
49
printf("\n::: new order ::: \n");
50
for (i=0;i<TOTAL_NUM;i++)
51
{
52
printf("%5ld ",Sort[i]);
53
if(++iPrintCount==10)
54
{
55
iPrintCount = 0;
56
printf("\n");
57
}
58
}
59
60
getchar();
61
return 0;
62
}

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

36



37

38



39

40

41

42

43

44

45

46

47

48

49

50

51



52

53

54



55

56

57

58

59

60

61

62

posted on 2009-07-20 23:48 xmoss 閱讀(450) 評論(0) 編輯 收藏 引用 所屬分類: 結構和算法