标签:style blog color io for div sp log amp
1 #include <stdio.h> 2 3 //直接插入排序算法 4 void InsertSort(int a[], int size) 5 { 6 int i, j; 7 int key; //待插入的值 8 for (j = 1; j < size; j++) 9 { 10 key = a[j]; 11 i = j - 1; 12 while (i >= 0 && a[i]>key) 13 { 14 a[i + 1] = a[i]; 15 i--; 16 } 17 a[i + 1] = key; 18 } 19 } 20 21 /* 22 Shell排序算法: 23 1)设置步长d=n/2; 24 2)分组进行直接插入排序 25 3)改变步长d=d/2,重复2)和3),直到d<=0; 26 */ 27 void ShellSort(int a[], int size) 28 { 29 int i, j, key; 30 int d = size / 2; //步长 31 32 while (d > 0) 33 { 34 for (j = d; j < size; j++) 35 { 36 i = j - d; 37 key = a[j]; 38 while (i >= 0 && a[i] > key) 39 { 40 a[i + d] = a[i]; 41 i = i - d; 42 } 43 a[i + d] = key; 44 } 45 d = d / 2; 46 } 47 } 48 49 //冒泡排序 50 void BubbleSort(int a[], int size) 51 { 52 int i, j, temp; 53 for (i = 0; i < size; i++) 54 { 55 for (j = size-1;j>i;j--) 56 { 57 if (a[j] < a[j - 1]) 58 { 59 temp = a[j]; 60 a[j] = a[j - 1]; 61 a[j - 1] = temp; 62 } 63 } 64 } 65 } 66 67 //快速排序 68 void QuickSort(int a[], int low, int high) 69 { 70 int temp_low = low; 71 int temp_high = high; 72 int i; 73 if (low < high) 74 { 75 int key,temp; 76 bool flag = true; 77 key = a[low]; 78 while (low<high) 79 { 80 if (flag) 81 { 82 if (a[high]<key) 83 { 84 temp = a[high]; 85 a[high] = a[low]; 86 a[low] = temp; 87 low++; 88 flag = false; 89 } 90 else 91 { 92 high--; 93 } 94 } 95 else 96 { 97 if (a[low]>key) 98 { 99 temp = a[high]; 100 a[high] = a[low]; 101 a[low] = temp; 102 high--; 103 flag = true; 104 } 105 else 106 { 107 low++; 108 } 109 } 110 111 } 112 i = low; 113 a[i] = key; 114 QuickSort(a, temp_low, i - 1); 115 QuickSort(a, i + 1, temp_high); 116 } 117 } 118 119 //直接选择排序 120 void SelectSort(int a[], int size) 121 { 122 int i, j; 123 int k; //存放最小值的下标 124 int temp; 125 for (i = 0; i < size; i++) 126 { 127 k = i; 128 for (j = i+1; j < size; j++) 129 { 130 if (a[j] < a[k]) 131 k = j; 132 } 133 temp = a[i]; 134 a[i] = a[k]; 135 a[k] = temp; 136 } 137 } 138 139 void main() 140 { 141 int a[10] = { 5, 4, 2, 5, 7, 9, 8, 1, 6, 0 }; 142 int i; 143 144 //InsertSort(a, 10); 145 //ShellSort(a, 10); 146 //BubbleSort(a, 10); 147 //QuickSort(a, 0, 9); 148 SelectSort(a, 10); 149 for (i = 0; i < 10; i++) 150 { 151 printf("%d ", a[i]); 152 } 153 154 printf("\n"); 155 }
标签:style blog color io for div sp log amp
原文地址:http://www.cnblogs.com/panlonyin/p/3958628.html