堆排序
//堆排序 //①维护堆 void max_heapify(int *ptr,int index,int len) { index = index + 1; int left = index << 1; int right = (index << 1) + 1; int largest = index; if(left <= len && ptr[left - 1] > ptr[index - 1]) largest = left; if(right <= len && ptr[right - 1] > ptr[largest - 1]) largest = right; if(largest != index) { swap(&ptr[index - 1],&ptr[largest - 1]); max_heapify(ptr,largest-1,len); } } //②建立堆 void build_max_heap(int* ptr,int len) { for(int i = len >> 1; i >= 0; --i) { max_heapify(ptr,i,len); } } //③堆排序 void heapSort(int* ptr,int len) { build_max_heap(ptr,len); for(int i = len - 1;i>0;--i) { swap(&ptr[0],&ptr[i]); max_heapify(ptr,0,i); } } int main() { int a[] = {2,23,45,1,8,2,0}; for(int i =0; i <= 6; ++i) { std::cout << a[i] << " "; } cout << endl; //mergeSort(a,0,6); //quickSort(a,0,6); heapSort(a,7); for(int i =0; i <= 6; ++i) { std::cout << a[i] << " "; } std::cout << std::endl; return 0; }