快速排序VS堆排序
简要的实现如下:
/************************************************************************* > File Name: heapsort.h > Author: zhoulin > Mail: 715169549@qq.com > Created Time: Wed Apr 13 12:52:15 2016 ************************************************************************/ #ifndef _HEAPSORT_H #define _HEAPSORT_H typedef struct _heap{ int *array; int heapsize; //heap size int len; //array len }heap; //swap a and b void swap(int *a,int *b); void adjust(heap *p,int i); void heap_sort(heap *p); //-------------split-------------- int parttion(int *arr,int left,int right); void quit_sort(int *arr,int start,int end); #endif
/************************************************************************* > File Name: hsort.c > Author: zhoulin > Mail: 715169549@qq.com > Created Time: Wed Apr 13 12:55:18 2016 ************************************************************************/ #include "hsort.h" #include <stdio.h> void swap(int *a,int *b) { *a = *a^*b; *b = *a^*b; *a = *a^*b; } void adjust(heap *p,int i) { if(p == NULL) return; int *array = p->array; int largest; int left = (i+1)<<1-1; int right = (i+1)<<1; int curmax = p->heapsize; if(left < curmax && array[left] > array[i]) { largest = left; }else{ largest = i; } if(right < curmax && array[right] > array[largest]) { largest = right; } if(largest != i) { swap(&array[largest],&array[i]); adjust(p,largest); } } void heap_sort(heap *p) { int *array = p->array; int i,len = p->len; for(i=(len>>1)-1;i>=0;i--) { fprintf(stdout,"build %d\n",i); adjust(p,i); } while(p->heapsize >0) { swap(&array[0],&array[p->heapsize]); p->heapsize--; adjust(p,0); } } int parttion(int *arr,int left,int right) { int cur = arr[left]; while(left < right && arr[right] >= cur) { right--; } if(left < right) { arr[left++] = arr[right]; } while(left < right && arr[left] <= cur) { left++; } if(left < right) { arr[right--] = arr[left]; } arr[left] = cur; return left; } void quit_sort(int *arr,int start,int end) { int pos; if(start <= end) { pos = parttion(arr,start,end); quit_sort(arr,0,pos-1); quit_sort(arr,pos+1,end); } } int main(void) { heap p; int i; int arr[9]={100,1,300,56,34,45,67,21,89}; /* p.array = (int *)&arr; */ int len = 9; for(i = 0;i< len;i++) { fprintf(stdout,"arr[%d] = %d\n",i,arr[i]); } fprintf(stdout,"-----------------------------------------\n\n"); quit_sort(arr,0,len-1); /* p.len = len; p.heapsize = p.len -1; heap_sort(&p); */ for(i = 0;i< len;i++) { fprintf(stdout,"arr[%d] = %d\n",i,arr[i]); } return 0; }
运行结果:
root@:/data/code/cwork/demo:./hsort arr[0] = 100 arr[1] = 1 arr[2] = 300 arr[3] = 56 arr[4] = 34 arr[5] = 45 arr[6] = 67 arr[7] = 21 arr[8] = 89 ----------------------------------------- arr[0] = 1 arr[1] = 21 arr[2] = 34 arr[3] = 45 arr[4] = 56 arr[5] = 67 arr[6] = 89 arr[7] = 100 arr[8] = 300