实现一个降序堆
class Heap {
int arr[];
int size;
public Heap(int[] arr) {
this.arr = arr;
this.size = arr.length;
this.buildHeap();
}
void buildHeap() {
for (int i = this.size / 2 - 1; i >= 0; i--) {
heapify(i);
}
}
void heapify(int root_index){
int max_index = root_index;
int left_child_index = 2 * root_index + 1;
int right_child_index = 2 * root_index + 2;
if (left_child_index < size && arr[left_child_index] > arr[max_index]) {
max_index = left_child_index;
}
if (right_child_index < size && arr[right_child_index] > arr[max_index]) {
max_index = right_child_index;
}
if (max_index != root_index) {
swap(arr, root_index, max_index);
heapify(max_index); // 正确的位置
}
}
void swap(int[] arr, int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
int getSize() {
return size;
}
int getMaxValue() {
if (size <= 0) return Integer.MIN_VALUE; // 边界条件检查
int max = arr[0]; // 最大值存到堆顶元素
arr[0] = arr[size - 1]; // 最小值移到堆顶,最大值移到最后
size--; // 堆大小-1,删除最大的值
heapify(0); // 再次从堆顶开始调整堆
return max;
}
}
class heapsort{
public static void main(String[] args) {
int[] num = {1,3,15,-1,3,4,25};
Heap h = new Heap(num);
int[] res = new int[num.length];
for (int i = 0; i < res.length; i++) {
res[i] = h.getMaxValue();
}
}
}
补充一个实现升序堆(力扣912的排序是要求升序的)
排序数组
class Solution {
public int[] sortArray(int[] nums) {
Heap h = new Heap(nums);
int[] res = new int[nums.length];
for (int i = 0; i < res.length; i++) {
res[i] = h.getMinValue();
}
return res;
}
}
class Heap {
int[] arr;
int size;
public Heap(int[] arr) {
this.arr = arr;
this.size = arr.length;
this.buildHeap();
}
void buildHeap() {
for(int i = this.size/2 - 1; i >= 0; i--) {
heapify(i);
}
}
void heapify(int root_index) {
int min_index = root_index;
int left_child = root_index * 2 + 1;
int right_child = root_index * 2 + 2;
if (left_child < size && arr[left_child] < arr[min_index]) {
min_index = left_child;
}
if (right_child < size && arr[right_child] < arr[min_index]) {
min_index = right_child;
}
if (min_index != root_index) {
swap(arr, root_index, min_index);
heapify(min_index);
}
}
void swap(int[] arr, int i, int j) {
int tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
int getMinValue() {
if (size <= 0) return Integer.MIN_VALUE;
int min = arr[0];
arr[0] = arr[size - 1];
size--;
heapify(0);
return min;
}
int getSize() {
return size;
}
}