优先列队(堆)也是一种树结构!!
package 数据结构与算法;
import java.util.Arrays;
public class 树_堆结构 {
public static void main(String[] args) {
int[] arr = {9, 6, 8, 7, 0 ,1, 10, 4, 2};
int start = (arr.length-1)/2;
heapSort(arr);
System.out.println(Arrays.toString(arr));
}
public static void heapSort(int[] arr) {
int start = (arr.length -1)/2;
for (int i = start; i >= 0; i--) minHeap(arr, arr.length, i);
for (int i = arr.length- 1; i > 0; i--) {
int temp = arr[0];
arr[0] = arr[i];
arr[i] = temp;
minHeap(arr, i, 0);
}
}
public static void maxHeap(int[] arr, int size, int index) {
int leftNode = 2*index+1;
int rightNode = 2*index+2;
int max = index;
if (leftNode < size && arr[leftNode] > arr[max]) max = leftNode;
if (rightNode < size && arr[rightNode] > arr[max]) max = rightNode;
if (max != index) {
int temp = arr[index];
arr[index] = arr[max];
arr[max] = temp;
maxHeap(arr, size, max);
}
}
public static void minHeap(int[] arr, int size, int index) {
int leftNode = 2*index+1;
int rightNode = 2*index+2;
int min = index;
if (leftNode < size && arr[leftNode] < arr[min]) min = leftNode;
if (rightNode < size && arr[rightNode] < arr[min]) min = rightNode;
if (min != index) {
int temp = arr[index];
arr[index] = arr[min];
arr[min] = temp;
minHeap(arr, size, min);
}
}
}