void heapInsert(int curArr[], int index)
{
while (curArr[index]>curArr[(index-1)/2])
{
swap(curArr[index], curArr[(index - 1) / 2]);
index = (index - 1) / 2;
}
}
void heapify(int curArr[], int heapSize)
{
int rootIndex = 0;
int leftIndex = rootIndex * 2 + 1;
while (leftIndex <heapSize)
{
int largIndex = 0;
int rigthIndex = leftIndex + 1;
if (rigthIndex < heapSize && curArr[rigthIndex]>curArr[leftIndex])
{
largIndex = rigthIndex;
}
else
{
largIndex = leftIndex;
}
if (curArr[largIndex] > curArr[rootIndex]) {
swap(curArr[largIndex], curArr[rootIndex]);
rootIndex = largIndex; // 当前要下窜的节点
leftIndex = rootIndex * 2 + 1;
}
else {
break;
}
}
}
//堆排:nlogn(时间) 1(空间) 不稳定
void heapSort(int curArr[],int length)
{
if (curArr == nullptr) return;
for (int i = 0; i < length; i++)
{
heapInsert(curArr, i);
for (int j = 0; j < length; j++) {
cout << ">>" << curArr[j];
}
cout << endl;
}
int heapSize = length;
while (heapSize > 0)
{
heapify(curArr, heapSize);
swap(curArr[0], curArr[heapSize-1]);
heapSize--;
for (int j = 0; j < length; j++) {
cout << ">>" << curArr[j];
}
cout << endl;
}
}```
选择排序之堆排
最新推荐文章于 2024-07-25 22:05:33 发布