写完的时候忘了贴出来,现在一起贴好了。这个demo很简答,简单选择、插入、快排和归并,别的有时间再练习好了。供刚入门的童鞋参考吧。^_^
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <time.h> 4 #define N 10 5 int a[N], b[N]; 6 void init_array(int l, int r) 7 { 8 int i; 9 srand(time(NULL)); 10 for(i=1;i<=r;i++) a[i]=rand()%100; 11 } 12 void show_array(int l, int r) 13 { 14 int i; 15 for(i=0;i<l;i++) printf(" "); 16 for(i=l;i<=r;i++) printf("%3d",a[i]); 17 printf("\n"); 18 } 19 void swap(int i, int j) 20 { 21 int tmp = a[i]; a[i] = a[j]; a[j] = tmp; 22 } 23 void selection_sort(int l, int r) 24 { 25 int i, j, min; 26 for(j=l;j<r;j++) 27 { 28 min = j; //j来初始化min的同时,位置被预留了 29 for(i=j+1; i<=r; i++) 30 if(a[i]<a[min]) min = i; 31 swap(min, j); 32 } 33 } 34 void insertion_sort(int l, int r) 35 { 36 int i, j, tmp; 37 for(j=l+1;j<=r;j++) 38 { 39 tmp = a[j]; //当前求插入的元素 40 for(i=j;i>l&&tmp<a[i-1];i--) 41 a[i] = a[i-1]; //大的右移 42 a[i] = tmp; 43 } 44 } 45 46 void merge(int l, int m, int r) 47 { 48 int i, j, k; 49 for(i=l;i<=r;i++) b[i] = a[i]; 50 i = l; j = m+1; k = l; 51 while(i<=m&&j<=r) 52 if(b[i]<b[j]) a[k++] = b[i++]; 53 else a[k++] = b[j++]; 54 while(i<=m) a[k++] = b[i++]; 55 while(j<=r) a[k++] = b[j++]; 56 } 57 58 void merge_sort(int l, int r) 59 { 60 if(l>=r) return; 61 int m = (l+r)/2; 62 merge_sort(l, m); 63 merge_sort(m+1, r); 64 merge(l, m, r); 65 } 66 67 int partition(int l, int r) 68 { 69 int i, j; 70 for(j=l,i=l+1;i<=r;i++) //最左端是哨兵 71 if(a[i]<a[l]) swap(i,++j); 72 swap(l, j); 73 return j; 74 } 75 76 void quick_sort(int l, int r) 77 { 78 if(l>=r) return; 79 int k = partition(l, r); 80 quick_sort(l, k-1); 81 quick_sort(k+1, r); 82 }