您的位置:首页 > 编程语言 > Java开发

堆排序的java实现

2012-06-10 20:30 399 查看
public class TreeUtils {
public static int getLeftSubNodeIndex(int current){
return 2*current;
}
public static int getRightSubNodeIndex(int current){
return 2*current+1;
}
public static int getParentNodeIndex(int current){
return Integer.parseInt(Double.toString(Math.floor(current/2)));
}
}

public class HeapSorter {

public void sort(int[] needSortArray){
if (needSortArray != null && needSortArray.length > 0){
int heapSize = needSortArray.length;
buildMaxHeap(needSortArray);
for (int i = heapSize -1; i > 0;i--){
int temp = needSortArray[0];
needSortArray[0] = needSortArray[i];
needSortArray[i] = temp;
maxHeapify(needSortArray,0,i);
}
}
}

public void buildMaxHeap(int[] array){
int heapSize = array.length;
for (int i = (heapSize - 1 )/2;i>=0;i--){
maxHeapify(array,i,heapSize);
}
}

public void maxHeapify(int[] array,int currentIndex,int heapSize){
int leftIndex = TreeUtils.getLeftSubNodeIndex(currentIndex);
int rightIndex = TreeUtils.getRightSubNodeIndex(currentIndex);
int maxIndex = currentIndex;
if (leftIndex < heapSize && array[leftIndex] > array[currentIndex]){
maxIndex = leftIndex;
}
if (rightIndex < heapSize && array[rightIndex] > array[maxIndex]){
maxIndex = rightIndex;
}
if (maxIndex != currentIndex){
int tempValue = array[currentIndex];
array[currentIndex] = array[maxIndex];
array[maxIndex] = tempValue;
maxHeapify(array,maxIndex,heapSize);
}
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: