排序算法:快速排序
堆排序:
1.堆调整
2.交换堆顶与最后
3.堆调整
数组下标默认从0开始
#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
using namespace std;
void AdjustDown(int R[],int parent,int n)
{
//默认左孩子
int child = parent * 2 + 1;
while (child < n)
{
if (child + 1 < n && R[child + 1] > R[child])
child = child + 1;
if (R[child] > R[parent])
{
swap(R[child], R[parent]);
parent = child;
child = parent * 2 + 1;
}
else
{
return;
}
}
}
void heapSort(int R[], int n)
{
int i;
int temp;
for (i = (n - 2) / 2; i >= 0; i--)
{
AdjustDown(R, i, n);
}
for (int i = n - 1; i >= 1; i--)
{
swap(R[0], R[i]);
AdjustDown(R, 0, i);
}
}
int main()
{
int R[] = { 49, 38, 65, 97, 76, 13, 27, 49 };
heapSort(R, 8);
system("pause");
return 0;
}
适用于关键字很多的场景,从10000个关键字中选出前10个最小的