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.
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
相关文章推荐
- heapsort堆排序(3种语言实现 c/java/python)
- [转载]堆排序(HeapSort) Java实现
- HeapSort堆排序Java实现图文代码详解
- 堆排序(Heap Sort)原理及Java实现
- 堆排序(HeapSort) Java实现
- 堆排序(Heapsort)之Java实现
- 堆排序(Heapsort)之Java实现
- 堆排序Heap Sort——浅显易懂+Java实现
- Java实现---堆排序 Heap Sort
- 堆排序(HeapSort)之java实现
- 堆排序heapSort java实现
- 堆排序(Heapsort)之Java实现
- Java堆排序(HeapSort)算法实现
- 堆排序Heap Sort——浅显易懂+Java实现
- 堆排序(Heapsort)之Java实现
- HeapSort的java语言实现
- Java实现堆排序(Heapsort)实例代码
- 堆排序(Heap Sort) 算法实现 C语言版
- Go语言标准库堆(heap)封装及堆排序实现
- 堆排序(java 语言实现)