选择、插入、冒泡排序

 1 #include<stdio.h>
 2 //#include<assert.h>
 3 
 4 bool BubbleSort(int A[],int n)
 5 {
 6 //    assert(A != NULL);
 7 //    assert(n != 0 );
 8     if (A==NULL || n<= 0)
 9     {
10         return false;
11     }
12 
13     for (int  i = 0 ; i < n -1 ; i++)
14     {
15         for (int  j = 0 ; j < n - i - 1 ; j++)
16         {
17             if (A[j]>A[j+1])
18             {
19                 int temp = A[j];
20                 A[j] = A[j+1];
21                 A[j+1] = temp;
22             }
23         }
24     }
25 
26     return true;
27 }
28 
29 
30 bool InsertSort(int A[],int n)
31 {
32     if (A==NULL||n<0)
33     {
34         printf("Parameter for function InsertSort error!\n");
35         return false;
36     }
37     for (int i=1;i<n;i++)
38     {
39         int val = A[i];//i的值表示待插入元素的下标
40         int j = i-1;   //j的值表示已经排好序的元素的最大下标(A[0]...A[i-1]已经有序)
41         while (j>=0&&A[j]<val) //降序(大的放前面)
42         {
43             A[j+1] = A[j];
44             j--;
45         }
46         //A[j]>=val,val插在j的后面
47         A[j+1] = val;
48     }
49 
50     return true;
51 }
52 
53 void SelectSort(int A[],int n)
54 {
55     int i,j;
56     for (i=0;i<n-1;i++) //对n-1个数排好序,所有数即排好序
57     {
58         for (j=i;j<n;j++)
59         {
60             if (A[i]<A[j]) //排成降序
61             {
62                 int temp = A[i];
63                 A[i] = A[j];
64                 A[j] = temp;
65             }
66         }
67     }
68     
69 }
70 
71 
72 void printArray(int A[] ,int n)
73 {
74     for (int i = 0 ;i<n;i++)
75     {
76         printf("%d  ",A[i]);
77     }
78     printf("\n");
79 }
80 
81 void main()
82 {
83     int A[10] = {3,2,6,9,12,32,41,23,21,79}; 
84 //    BubbleSort(A,10);
85 //    InsertSort(A,10);
86     SelectSort(A,10);
87     printArray(A,10);
88 }

 

 

 

posted @ 2013-09-10 10:23  Big.Eagle  阅读(199)  评论(0)    收藏  举报