public int[] SiftFromSmaller(int[] list, int low, int high) //小根堆排序基本程序
{
int i = low;
int j = 2 * i + 1;
int sortNum = list[i];
while (j <= high)
{
if ((j + 1) <= high && list[j + 1] < list[j])
{
j = j + 1;
}
if (list[j] < sortNum)
{
list[i] = list[j];
i = j;
j = 2 * i + 1;
}
else
{
break;
}
list[i] = sortNum;
for (int l = 0; l < list.Length; ++l)
{
Console.WriteLine(list[l]);
}
Console.WriteLine("Over");
}
return list;
}
public int[] Heap(int[] list)//形成堆
{
for (int i = (list.Length - 2)/2; i >= 0; --i)
{
SiftFromSmaller(list, i, list.Length - 1);
}
return list;
}
public int[] HeapSort(int[] list) //堆排序
{
int right = list.Length;
int i = 0;
for (i = right - 1; i >= 0; --i)
{
int storeNum = list[0];
list[0] = list[i];
list[i] = storeNum;
SiftFromSmaller(list, 0, i - 1);
}
return list;
}
public int[] TopKSort(int[] list, int k)//TopK
{
if(k > list.Length)
{
int[] nullList = null;
return nullList;
}
int[] listK = new int[k];
for(int i = 0; i < k; ++i)
{
listK[i] = list[i];
}
Program toolOfHeapsort = new Program();
toolOfHeapsort.Heap(list);
toolOfHeapsort.HeapSort(list);
for(int n = k; n < list.Length; ++n)
{
if (list[k] <= listK[0]) continue;
listK[0] = list[k];
toolOfHeapsort.HeapSort(listK);
}
return listK;
}
以上为学习路飞学城教程有感而练习