import org.junit.Test;
import java.util.Arrays;
public class DuiPai {
//主方法
public void LargeHeap(int[] arr){
if(arr == null || arr.length < 1){
return;
}
for (int i = 0; i < arr.length; i++) {
largeInsert(arr, i);
}
int heapSize = arr.length-1;
swap(arr, 0, heapSize);
while(heapSize > 0){
heapify(arr, 0, heapSize--);
swap(arr, 0, heapSize);
}
}
public void largeInsert(int[] arr, int i){
//在存在的大根堆上插入节点
int tmp;
while (arr[i] > arr[(i-1)/2]) {
swap(arr, i, (i-1)/2);
i = (i-1)/2;
}
}
public void heapify(int[] arr, int index, int size){
//调整其中任意一个节点,使整体形成大根堆
int left = index * 2 + 1;
while(left < size){
int largest = left + 1 < size && arr[left + 1] > arr[left] ? left + 1 : left;
largest = arr[largest] > arr[index] ? largest : index;
if(largest == index){
break;
}
swap(arr, largest, index);
index = largest;
left = index * 2 + 1;
}
}
public void swap(int[] arr, int i, int j){
//交换两个节点
int tmp;
tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
@Test
public void test(){
//测试方法
int[] arr = {4,5,6,3,7,2,8};
LargeHeap(arr);
System.out.println(Arrays.toString(arr));
}
}
|