C language Sorting Algorithm summary, C language Sorting Algorithm
1 #include <stdio.h>
2 #include <stdlib.h>
// Author: Kailugaji - blog http://www.cnblogs.com/kailugaji/ Park
3 #define N 20
4 // bubble sort
5 void bubble (int a [], int n) {
6 int i, j, temp;
7 for (i = 0; i <n-1; i ++) {
8 for (j = 0; j <n-1-i; j ++) {
9 if (a [j]> a [j + 1]) {
10 temp = a [j];
11 a [j] = a [j + 1];
12 a [j + 1] = temp;
13}
14}
15}
16}
17
18 // select sort
19 void select (int a [], int n) {
20 int i, j, min, temp;
21 for (i = 0; i <n-1; i ++) {
22 min = i;
23 for (j = i + 1; j <n; j ++) {
24 if (a [j] <a [min]) {
25 min = j;
26}
27}
28 if (min! = I) {
29 temp = a [i];
30 a [i] = a [min];
31 a [min] = temp;
32}
33}
34}
35 // Inline sort
36 void insert (int a [], int n) {
37 int i, j, temp;
38 for (i = 1; i <n; i ++) {
39 temp = a [i];
40 j = i-1;
41 while ((temp <a [j]) && (j> = 0)) {
42 a [j + 1] = a [j];
43 j--;
44}
45 a [j + 1] = temp;
46}
47}
48 // Half Insertion Sort
49 void bi_insert (int a [], int n) {
50 int i, j, low, high, mid, temp;
51 for (i = 1; i <n; i ++) {
52 temp = a [i];
53 low = 0;
54 high = i-1;
55 while (low <= high) {
56 mid = (low + high) / 2;
57 if (a [mid]> temp) {
58 high = mid-1;
59}
60 else
61 low = mid + 1;
62}
63 for (j = i-1; j> = high + 1;-j) {
64 a [j + 1] = a [j];
65}
66 a [high + 1] = temp;
67}
68}
69 // heap sort
70 void sift (int a [], int low, int high) {
71 int i = low, j = i * 2, t = a [i];
72 while (j <= high) {
73 if (j <high && a [j] <a [j + 1]) {
74 ++ j;
75}
76 if (t <a [j]) {
77 a [i] = a [j];
78 i = j;
79 j = 2 * i;
80}
81 else
82 break;
83}
84 a [i] = t;
85}
86
87 void heap (int a [], int n) {
88 int i, temp;
89 for (i = n / 2; i> = 1;-i) {
90 sift (a, i, n);
91}
92 for (i = n; i> = 2;-i) {
93 temp = a [i];
94 a [i] = a [1];
95 a [1] = temp;
96 sift (a, 1, i-1);
97}
98}
99
100
101 void main () {
102 int a [N];
103 int i, k, m;
104 printf ("Please input a number:");
105 scanf ("% d", & m);
106 printf ("Please input% d numbers: \ n", m);
107 for (i = 0; i <m; i ++) {
108 scanf ("% d", a + i);
109}
110 while (1) {
111 printf ("1. Bubble sort \ n2. Select sort \ n3. Direct insert sort \ n4. Half insert sort \ n5. Heap sort \ n0.exit \ nPlease choose:");
112 scanf ("% d", & k);
113 switch (k)
114 {
115 case 1: bubble (a, m); break;
116 case 2: select (a, m); break;
117 case 3: insert (a, m); break;
118 case 4: bi_insert (a, m); break;
119 case 5: heap (a, m-1); break;
120 case 0: printf ("Byebye! \ N"); system ("pause"); exit (0);
121 default: printf ("Input error! \ NPlease choose again: \ n"); continue;
122}
123 printf ("Result: \ n");
124 for (i = 0; i <m; i ++) {
125 printf ("% 4d", a [i]);
126}
127 printf ("\ n");
128}
129 system ("pause");
130}