快速排序实现
int divide(int arr[],int first,int second) { int ele = arr[first]; while(first < second) { while(second > first && arr[second] >= ele) second--; if(second > first) { arr[first] = arr[second]; first++; } while(second > first && ele > arr[first]) first++; if(second > first) { arr[second] = arr[first]; second--; } } arr[first] = ele; return first; } void quick_sort(int arr[],int first,int second) { if(first >= second) return; int index = divide(arr,first,second); quick_sort(arr,first,index - 1); quick_sort(arr,index + 1,second); } void quick_sort(int arr[],int len) { quick_sort(arr,0,len - 1); }
void build_heap(int arr[],int len); void adjust_down(int arr[],int len,int rt); void heap_sort(int arr[],int len) { build_heap(arr,len); for(int i = 0; i < 10;i++) printf("%d ",arr[i]); printf("\n"); for(int i = len - 1;i >= 1;i--) { swap(arr[0],arr[i]); adjust_down(arr,i,0); } } void build_heap(int arr[],int len) { for(int i = (len - 1)/2; i >= 0;i--) adjust_down(arr,len,i); } void adjust_down(int arr[],int len,int rt) { while(rt < len) { int minx = arr[rt],son = -1; if(rt*2+1 < len && arr[rt*2+1] < minx) minx = arr[rt*2+1],son = rt*2+1; if(rt*2+2 < len && arr[rt*2+2] < minx) minx = arr[rt*2+2],son = rt*2+2; if(minx < arr[rt]) { swap(arr[rt],arr[son]); rt = son; } else { break; } } }