상용 정렬 알고리즘 집합 - C 구현

전에 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
" "-b show unsorted status
" "-m merge sort
" "-i insertion sort
" "-I Information
" "-h help and exit
"); return; } static void usage_info(void) { printf("
" "
"); 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
",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 :
"); print_r(arr,MAX); printf("=========================================
"); break; case 'h': usage(); break; case 's': selection_sort(arr,MAX); printf("selection sorting :
"); sorted = 1; break; case 'i': insertion_sort(arr); printf("insertion sorting :
"); sorted = 1; break; case 'm': merge_sort(arr,0,MAX-1); printf("merge sorting :
"); sorted = 1; break; case 'I': usage_info(); break; default : usage(); break; } } if(sorted) { print_r(arr,MAX); } } else { usage(); exit(0); } }

좋은 웹페이지 즐겨찾기