#include using namespace std; //快速排序,在子函数中,数组已被改变 void quick_sort(int *a, int left, int right) //left和right为索引值 { int temp; //存储每次选定的基准数(从最左侧选基准数) int t; int initial=left; int end=right; temp=a[left]; //***必须有这一部分***// if (left>right) //因为在递归过程中有减1加1的情况,当其越界时,直接return,不返回任何值,即结束当前程序块 return; while(left!=right) //此时左右index在移动中,若left==right,则跳出循环,将基数归位 { while(a[right]>=temp && left 0;--i){
int temp = arr[i];
arr[i] = arr[0];
arr[0] = temp;
//调整成堆
Heapify(arr,0,i);
}
}
再看 调整成堆的函数
void Heapify(int arr[], int first, int end){
int father = first;
int son = father * 2 + 1;
while(son < end){
if(son + 1 < end && arr[son] < arr[son+1]) ++son;
//如果父节点大于子节点则表示调整完毕
if(arr[father] > arr[son]) break;
else {
//不然就交换父节点和子节点的元素
int temp = arr[father];
arr[father] = arr[son];
arr[son] = temp;
//父和子节点变成下一个要比较的位置
father = son;
son = 2 * father + 1;
}
}
}
堆排序的时间复杂度最好到最坏都是O(nlogn),较多元素的时候效率比较高