快速排序
void quick_sort(int array[], int begin, int end) { if(end > begin) { int pivot = begin; int last_small = begin; int i = end; while(last_small != i) { if(array[i] <= array[pivot]) { int temp = array[i]; array[i] = array[++last_small]; array[last_small] = temp; } else i--; } int tmp = array[pivot]; array[pivot] = array[last_small]; array[last_small] = tmp; quick_sort(array, begin, last_small - 1); quick_sort(array, last_small + 1, end); } }
堆排序
void adjust_heap(int[], int, int); void build_heap(int array[], int size)//build the max-heap { for(int i = size - 1; i >= 0; i--) { adjust_heap(array, size, i); } } void adjust_heap(int array[], int size, int element)//adjust the max-heap { int left = element * 2 + 1; int right = left + 1; while(right < size) { if(array[element] >= array[left] && array[element] >= array[right]) return; if(array[left] >= array[right]) { int tmp = array[left]; array[left] = array[element]; array[element] = tmp; element = left; } else { int tmp = array[right]; array[right] = array[element]; array[element] = tmp; element = right; } left = element * 2 + 1; right = left + 1; } if(left < size && array[left] > array[element]) { int tmp = array[left]; array[left] = array[element]; array[element] = tmp; } } void heap_sort(int array[], int size)//heap sort { build_heap(array, size); for(int i = size - 1; i > 0; i--) { int tmp = array[i]; array[i] = array[0]; array[0] = tmp; adjust_heap(array, i, 0); } }
时间: 2024-10-17 14:56:24