之前熟悉C的时候写着玩的,就当做笔记用吧:
#include<stdio.h> #include<stdlib.h> #include<string.h> #include<math.h> #define MAX 8 void print_r(int *arr,int len); static void usage(void) { printf("-s selection sort\n" "-b show unsorted status\n" "-m merge sort\n" "-i insertion sort\n" "-I Information\n" "-h help and exit\n"); return; } static void usage_info(void) { printf("这是一个排序算法的测试程序\n" "目前包括选择排序,插入排序和合并排序\n"); return; } int* create_arr(int *arr) { srand(time(NULL)); int i; for(i=0;i<MAX;i++) { arr[i]=rand()%100; } return arr; } void insertion_sort(int arr[]) { int temp = 0,j = 0,i = 0; for(j = 1;j<MAX;j++) { i = j-1; temp = arr[j]; while(i >= 0 && arr[i] < temp) { arr[i+1] = arr[i]; i--; } arr[i+1] = temp; } } void selection_sort(int arr[],int len) { int i,j=0,index,key; for(i=0;i < len;i++) { key = arr[i]; index = i; j = i+1; while(j < len) { if(arr[j] < key) { key = arr[j]; index = j; } j++; } arr[index] = arr[i]; arr[i] = key; } } /** * start 数组开始下标 * mid 数组分割下标 * end 数组结束下标 */ void merge(int arr[],int start,int mid,int end) { int szie_L,szie_R,i,j,k; szie_L = mid+1-start; //左数组大小 szie_R = end-mid; //右数组大小 int arr_L[szie_L],arr_R[szie_R]; for(i = 0;i < szie_L;i++) { arr_L[i] = arr[start+i]; } for(j = 0;j < szie_R;j++) { arr_R[j] = arr[mid+j+1]; } i = 0; j = 0; for(k = start;k <= end;k++) { if((i < szie_L) && (j < szie_R)) { if(arr_L[i] <= arr_R[j]) { arr[k] = arr_L[i]; i++; } else if(arr_L[i] > arr_R[j]) { arr[k] = arr_R[j]; j++; } } else if(j >= szie_R) { arr[k] = arr_L[i]; i++; } else { arr[k] = arr_R[j]; j++; } } } /** * start 数组开始下标 * end 数组结束下标 */ void merge_sort(int arr[],int start,int end) { int mid; //用来分割数组的下标 if(start < end) { mid = (int)((start+end)/2); merge_sort(arr,start,mid); merge_sort(arr,mid+1,end); merge(arr,start,mid,end); } } void print_r(int *arr,int len) { int i; for(i=0;i<len;i++) { printf("[%d]=>%d\n",i,arr[i]); } } void main(int argc ,char **argv) { int i,c,sorted=0; int arr[MAX]; create_arr(arr); if(argc>1) { while(-1 != (c = getopt(argc,argv,"hsimIb"))) { switch(c) { case ‘b‘: printf("before sorting : \n"); print_r(arr,MAX); printf("=========================================\n"); break; case ‘h‘: usage(); break; case ‘s‘: selection_sort(arr,MAX); printf("selection sorting : \n"); sorted = 1; break; case ‘i‘: insertion_sort(arr); printf("insertion sorting : \n"); sorted = 1; break; case ‘m‘: merge_sort(arr,0,MAX-1); printf("merge sorting : \n"); sorted = 1; break; case ‘I‘: usage_info(); break; default : usage(); break; } } if(sorted) { print_r(arr,MAX); } } else { usage(); exit(0); } }
时间: 2024-10-17 06:33:39