如图,以下是我的代码,刚开始学习数据结构这块,请教一下,是不是哪里出了逻辑问题?
package com.orange.exer;
public class HeapSort{
public static void heapSort(int[] arr){
if(arr == null || arr.length < 2){
return;
}
for(int i = (arr.length - 1) / 2;i >= 0;i--){
heapify(arr,i,arr.length);
}
int heapSize = arr.length;
swap(arr,0,--heapSize);
while(heapSize > 0){
heapify(arr,0,arr.length);
swap(arr,0,--heapSize);
}
}
public static void heapify(int[] arr,int heapSize,int index){
int left = index * 2 + 1;
while(left < heapSize){
int largest = left + 1 < heapSize && (arr[left] > arr[left + 1]) ? left : left + 1;
largest = arr[index] > arr[largest] ? index : largest;
if(largest == index) {
break;
}
swap(arr,index,largest);
index = largest;
left = index * 2 + 1;
}
}
public static void swap(int[] arr,int i,int j){
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
public static void main(String[] args){
int[] arr = {12,3,7,54,2,4,0,1,50};
heapSort(arr);
for(int i : arr){
System.out.print(i + ", ");
}
}
}
运行结果是这样的:
3, 7, 54, 2, 4, 0, 1, 50, 12,