我按照网上的算法实现了一边发现一个问题,list[0],无法参与排序,仔细查看算法实现过程,的确i =0,无法确定双亲(i/2),也无法确定左右孩子,解决办法构造二叉树时,左孩子是2i+1,右孩子是2i+2,更正后源代码:
1.测试代码
public class TestSort {
public static void main(String[] args) {
int []list ={8,9,7,6,5,4,3,2,1};
HeapSort.HeapSort(list);
System.out.println("输出排序后数组:");
for (int i=0 ;i <list.length ; i++){;
System.out.print(list[i] + " ");
}
}
}
2.堆排序代码
public class HeapSort
{
public static int heap_size;
public static int parent(int i)
{
return i-1/2;
}
public static int leftchild(int i)
{
return 2*i+1 ;
}
public static int rightchild(int i)
{
return 2 *i + 2;
}
public static void max_heapify(int []list,int i){
int left =leftchild(i);
int right =rightchild(i);
int largest = 0;
if (left <heap_size &&list[left] > list[i]){
largest =left;
}
else
{
largest = i;
}
if(right <heap_size && list[right] > list[largest]){
largest = right;
}
if (largest == i){
return;
}
else {
int temp =list[i];
list[i] = list[largest];
list[largest] = temp;
max_heapify(list,largest);
}
}
public static void Build_max_heap(int []list){
for (int i = list.length /2; i >=0 ; i--){
max_heapify(list , i);
}
}
public static void HeapSort(int []list){
heap_size =list.length;
Build_max_heap(list);
for(int i = list.length - 1 ;i >= 1 ; i-- ){
int temp = list[0];
list[0] = list[i];
list[i] = temp ;
heap_size-- ;
max_heapify(list, 0);
}
}
}