插入排序#include <stdio.h> #define LEN 5 int a[LEN] = {10, 5, 2, 4, 7}; void insertion_sort(void) { int i, j, key; for (j=1; j<LEN; j++) { printf("%d,%d,%d,%d,%d\n", a[0], a[1], a[2], a[3], a[4]); key = a[j]; i = j - 1; /* move, find the location */ while (i>=0 && a[i]>key) { a[i+1] = a[i]; i--; } a[i+1] = key; } printf("%d,%d,%d,%d,%d\n", a[0], a[1], a[2], a[3], a[4]); } int main(void) { insertion_sort(); return 0; }
如何验证以上代码是正确的 ? ( Loop Invariant 概念和数学归纳法 )
Loop Invariant ( 满足以下 3 个规则 )
例如以上的插入排序
这样就满足了以上的 Loop Invariant 。
算法描述:先把序列分成 n/2 的两个子序列,再分别对子序列使用归并排序,最后合并成一个最终的排序序列。在描述的步骤过程中,可以很明显的感觉到是一个递归的过程。
归并排序/* * Guibing sort * author : kevin * date : 2012.09.29 */ #include<stdio.h> #define LEN 8 int a[LEN] = {5, 2, 4, 7, 1, 3, 2, 6}; /* merge, concatenate */ void merge(int start, int mid, int end) { int n1 = mid - start + 1; int n2 = end - mid ; int left[n1], right[n2]; int i, j, k; for (i=0; i<n1; i++) { left[i] = a[start+i]; } for (j=0; j<n2; j++) { right[j] = a[mid+1+j]; } i = j = 0; k = start; while (i<n1 && j<n2) { if (left[i] < right[j]) { a[k++] = left[i++]; } else { a[k++] = right[j++]; } } while (i < n1) { a[k++] = left[i++]; } while (j < n2) { a[k++] = right[j++]; } } /* divide */ void sort(int start, int end) { int mid; if (start < end) { mid = (end + start) / 2; printf("sort(%d - %d,%d - %d) %d %d %d %d" "%d %d %d %d\n", start, mid, mid+1, end, a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7]); sort(start, mid); sort(mid+1, end); merge(start, mid, end); printf("merge(%d - %d,%d - %d) %d %d %d %d" "%d %d %d %d\n", start, mid, mid+1, end, a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7]); } } int main(void) { sort(0, LEN-1); return 0; }
线性查找/* line find * author : kevin * date : 2012.09.29 */ #include <stdio.h> char a[] = "hello world"; int indexof(char letter) { int i = 0; while (a[i] != '\0') { if (a[i] == letter) return i; i++; } return -1; } int main(void) { printf("%d %d\n", indexof('o'), indexof('z')); return 0; }
折半查找/* * half find * author : kevin * date : 2012.09.29 */ #include <stdio.h> #define LEN 8 int a[LEN] = {1, 2, 2, 2, 5, 6, 8, 9}; int binarysearch(int number) { int mid, start = 0, end = LEN - 1; while (start <= end) { mid = (start + end) / 2; if (a[mid]<number) start = mid + 1; else if (a[mid] > number) end = mid - 1; else return mid ; } return -1; } int main(void) { printf("%d\n", binarysearch(5)); return 0; }