1 #include<stdio.h>
2 #include<stdlib.h>
3
4 int main()
5 {
6 void arr_print(int* a,int n); //打印数组
7 void burble_sort(int *a,int n); //冒泡排序
8 void select_sort(int *a,int n); //选择排序
9 void shell_sort(int *a,int n); //希尔排序
10 void quick_sort(int a[],int left,int right);//快速排序
11 void insertion_sort(int a[],int len);//插入
12 int a[10]= {1,4,6,3,7,8,68,9,5,12};
13 printf("原始数据:\n");
14 arr_print(a,10);
15
16 printf("冒泡排序:\n");
17 burble_sort(a,10);
18
19 printf("选择排序:\n");
20 select_sort(a,10);
21
22 printf("希尔排序:\n");
23 shell_sort(a,10);
24
25 printf("快速排序;\n");
26 quick_sort(a,5,5);
27
28 printf("插入排序:\n");
29 insertion_sort( a,10);
30 return 0;
31 }
32 /****显示数据****/
33 void arr_print(int *a,int n)
34 {
35 int i=0;
36 for(i=0; i<n; i++)
37 {
38 printf("%3d",a[i]);
39 }
40 printf("\n");
41 }
42 /*****冒泡排序******/
43 void burble_sort(int *a,int n)
44 {
45 int i=0,j=0;
46 for(i=0; i<n; i++)
47 {
48 for(j=0; j<n-i-1; j++)
49 {
50 if(a[j]>a[j+1])
51 {
52 int temp;
53 temp=a[j];
54 a[j]=a[j+1];
55 a[j+1]=temp;
56 }
57 }
58 }
59 arr_print(a,10);
60 }
61 /*****选择排序*****/
62 void select_sort(int *a, int n)
63 {
64 int i, j, index, value;
65 for (i = 0; i < n - 1; i ++)
66 {
67 index = i; //记录当前下标
68 value = a[i]; //保留当前值
69 for (j = i + 1; j < n; j ++)
70 {
71 if (value > a[j])
72 {
73 index = j; //交换下标
74 value = a[j];//交换值
75 }
76 a[index] = a[i];
77 a[i] = value;
78 }
79 }
80 arr_print(a,10);
81 }
82 /*****希尔排序****/
83 void shell_sort(int *a,int n)
84 {
85 int j,i,key;
86 int gap=0;
87 if( n <= 0 || a == NULL )
88 {
89 return;
90 }
91 while( gap <= n )
92 {
93 gap = gap*3+1;
94 }
95 while( gap > 0 )
96 {
97 for( i=gap; i<n; i++ )
98 {
99 j = i-gap;
100 key = a[i];
101 while ( (j >= 0) && (a[j] > key) )
102 {
103 a[j+gap] = a[j];
104 j = j-gap;
105 }
106 a[j+gap] = key;
107 }
108 //display_array(len,a,gap);
109 gap = (gap - 1)/3;
110 }
111 arr_print(a,10);
112 }
113 /****快速排序*****/
114 void quick_sort(int a[],int left,int right)
115 {
116 int i,j,temp;
117 i=left;
118 j=right;
119 temp=a[left];
120 if(left>right)
121 return;
122 while(i!=j)/**//*找到最终位置*/
123 {
124 while(a[j]>=temp && j>i)
125 j--;
126 if(j>i)
127 a[i++]=a[j];
128
129 while(a[i]<=temp && j>i)
130 i++;
131 if(j>i)
132 a[j--]=a[i];
133 }
134 a[i]=temp;
135 quick_sort(a,left,i-1);/**//*递归左边*/
136 quick_sort(a,i+1,right);/**//*递归右边*/
137 arr_print(a,10);
138 return 0;
139 }
140 /*****插入排序******/
141 void insertion_sort( int a[], int len)
142 {
143 int j,i,key;
144 if( len <= 0 )
145 return;
146 for( j=1; j<len; ++j )
147 {
148 key = a[j];
149 i = j - 1;
150 while ( i >= 0 && a[i] > key )
151 {
152 a[i+1] = a[i];
153 --i;
154 }
155 a[i+1] = key;
156 }
157 arr_print(a,10);
158 }