堆排序

An Example of Heapsort:

Given an array of 6 elements: 15, 19, 10, 7, 17, 16, sort it in ascending order using heap sort.

Steps:

  1. Consider the values of the elements as priorities and build the heap tree.
  2. Start deleteMin operations, storing each deleted element at the end of the heap array.

After performing step 2, the order of the elements will be opposite to the order in the heap tree. 
Hence, if we want the elements to be sorted in ascending order, we need to build the heap tree 
in descending order - the greatest element will have the highest priority.

Note that we use only one array , treating its parts differently:

  1. when building the heap tree, part of the array will be considered as the heap, 
    and the rest part - the original array.
  2. when sorting, part of the array will be the heap, and the rest part - the sorted array.

This will be indicated by colors: white for the original array, blue for the heap and red for the sorted array

Here is the array: 15, 19, 10, 7, 17, 6

  1. Building the heap treeThe array represented as a tree, complete but not ordered:

    Start with the rightmost node at height 1 - the node at position 3 = Size/2. 
    It has one greater child and has to be percolated down:

    After processing array[3] the situation is:

    Next comes array[2]. Its children are smaller, so no percolation is needed.

    The last node to be processed is array[1]. Its left child is the greater of the children. 
    The item at array[1] has to be percolated down to the left, swapped with array[2].

    As a result the situation is:

    The children of array[2] are greater, and item 15 has to be moved down further, swapped with array[5].

    Now the tree is ordered, and the binary heap is built.

  2. Sorting - performing deleteMax operations:

    1. Delete the top element 19.

    1.1. Store 19 in a temporary place. A hole is created at the top

    1.2. Swap 19 with the last element of the heap. 

    As 10 will be adjusted in the heap, its cell will no longer be a part of the heap. 
    Instead it becomes a cell from the sorted array

    1.3. Percolate down the hole

    1.4. Percolate once more (10 is less that 15, so it cannot be inserted in the previous hole)

    Now 10 can be inserted in the hole

    2. DeleteMax the top element 17

    2.1. Store 17 in a temporary place. A hole is created at the top

    2.2. Swap 17 with the last element of the heap. 

    As 10 will be adjusted in the heap, its cell will no longer be a part of the heap.
    Instead it becomes a cell from the sorted array

    2.3. The element 10 is less than the children of the hole, and we percolate the hole down:

    2.4. Insert 10 in the hole

    3. DeleteMax 16

    3.1. Store 16 in a temporary place. A hole is created at the top

    3.2. Swap 16 with the last element of the heap. 

    As 7 will be adjusted in the heap, its cell will no longer be a part of the heap.
    Instead it becomes a cell from the sorted array

    3.3. Percolate the hole down (7 cannot be inserted there - it is less than the children of the hole)

    3.4. Insert 7 in the hole

    4. DeleteMax the top element 15

    4.1. Store 15 in a temporary location. A hole is created.

    4.2. Swap 15 with the last element of the heap. 

    As 10 will be adjusted in the heap, its cell will no longer be a part of the heap. 
    Instead it becomes a position from the sorted array

    4.3. Store 10 in the hole (10 is greater than the children of the hole)

    5. DeleteMax the top element 10.

    5.1. Remove 10 from the heap and store it into a temporary location.

    5.2. Swap 10 with the last element of the heap. 

    As 7 will be adjusted in the heap, its cell will no longer be a part of the heap. Instead it becomes a cell from the sorted array

    5.3. Store 7 in the hole (as the only remaining element in the heap

    7 is the last element from the heap, so now the array is sorted

Java实现:

public class HeapSort {
	private static int[] sort = new int[]{1,0,10,20,3,5,6,4,9,8,12,17,34,11};
	public static void main(String[] args) {
		buildMaxHeapify(sort);
		heapSort(sort);
		print(sort);
	}

	private static void buildMaxHeapify(int[] data){
		//没有子节点的才需要创建最大堆,从最后一个的父节点开始
		int startIndex = getParentIndex(data.length - 1);
		//从尾端开始创建最大堆,每次都是正确的堆
		for (int i = startIndex; i >= 0; i--) {
			maxHeapify(data, data.length, i);
		}
	}
	
	/**
	 * 创建最大堆
	 * @param data
	 * @param heapSize需要创建最大堆的大小,一般在sort的时候用到,因为最多值放在末尾,末尾就不再归入最大堆了
	 * @param index当前需要创建最大堆的位置
	 */
	private static void maxHeapify(int[] data, int heapSize, int index){
		// 当前点与左右子节点比较
		int left = getChildLeftIndex(index);
		int right = getChildRightIndex(index);
		
		int largest = index;
		if (left < heapSize && data[index] < data[left]) {
			largest = left;
		}
		if (right < heapSize && data[largest] < data[right]) {
			largest = right;
		}
		//得到最大值后可能需要交换,如果交换了,其子节点可能就不是最大堆了,需要重新调整
		if (largest != index) {
			int temp = data[index];
			data[index] = data[largest];
			data[largest] = temp;
			maxHeapify(data, heapSize, largest);
		}
	}
	
	/**
	 * 排序,最大值放在末尾,data虽然是最大堆,在排序后就成了递增的
	 * @param data
	 */
	private static void heapSort(int[] data) {
		//末尾与头交换,交换后调整最大堆
		for (int i = data.length - 1; i > 0; i--) {
			int temp = data[0];
			data[0] = data[i];
			data[i] = temp;
			maxHeapify(data, i, 0);
		}
	}
	
	/**
	 * 父节点位置
	 * @param current
	 * @return
	 */
	private static int getParentIndex(int current){
		return (current - 1) >> 1;
	}
	
	/**
	 * 左子节点position注意括号,加法优先级更高
	 * @param current
	 * @return
	 */
	private static int getChildLeftIndex(int current){
		return (current << 1) + 1;
	}
	
	/**
	 * 右子节点position
	 * @param current
	 * @return
	 */
	private static int getChildRightIndex(int current){
		return (current << 1) + 2;
	}
	
	private static void print(int[] data){
		int pre = -2;
		for (int i = 0; i < data.length; i++) {
			if (pre < (int)getLog(i+1)) {
				pre = (int)getLog(i+1);
				System.out.println();
			} 
			System.out.print(data[i] + " |");
		}
	}
	
	/**
	 * 以2为底的对数
	 * @param param
	 * @return
	 */
	private static double getLog(double param){
		return Math.log(param)/Math.log(2);
	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值