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

Heap Sort堆排序 Java语言实现

2018-03-16 14:36 676 查看
A binary heap is a complete binary tree which stores the following property:
1: It's a complete tree. Every row is full, except the bottom row.
2. A binary heap is either a MaxHeap( the key in a parent node is always greater than or equal to its child node.) or a MinHeap.( the key in a parent node is always less than or equal to its child node.)
Array List Representation of Heap:

If v is the root of heap T, then level number p(v)=1
If v is the left child of node u, then p(v)=2*p(u)+1
If v is the right child of node u, then p(v)=2*p(u)+2 

Heap Sort:
Three steps:

Build a heap and heapify the heap to restore order property(MaxHeap)
Swap the first node and the last node, reduce the heap size by 1. Heapify the root
Repeat the above step until the size of heap is greater than 1.
package com.heapDemo;

public class HeapSortDemo {
public static void main(String[] args) {
int[] arr = {2, 4, 1, 5, 8, 9, 10};
HeapSortDemo hs = new HeapSortDemo();
hs.heapsort(arr);
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}

}

private void heapsort(int arr[]) {
//step1: build a heap
int size = arr.length;
for (int i = size - 1; i >= 0; i--) {
heapify(arr, size, i);
}
//step2: swap and heapify
for (int i = size - 1; i >= 0; i--) {
int temp = arr[i];
arr[i] = arr[0];
arr[0] = temp;
heapify(arr, i, 0);
}

}

private void heapify(int arr[], int size, int i) {
int largest = i;
int left = 2 * i + 1;
int right = 2 * i + 2;
if (left < size && arr[left] > arr[largest]) {
largest = left;
}
if (right < size && arr[right] > arr[largest]) {
largest = right;
}
if (largest != i) {
int temp = arr[i];
arr[i] = arr[largest];
arr[largest] = temp;
heapify(arr, size, largest);
}
}
}


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