Home  >  Article  >  Java  >  What is heap sort in java? Introduction to heap sort

What is heap sort in java? Introduction to heap sort

青灯夜游
青灯夜游forward
2018-10-22 17:59:563162browse

This article brings you what is heap sorting in Java? Introduction to heap sort. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

  • Heap sorting introduction:
    Heap sorting can be divided into two stages. In the heap construction phase, we reorganize the original array into a heap; then in the sinking sort phase, we remove all elements from the heap in order and get the sorted result.
    1. Heap construction, an effective method is to use the sink() sinking function from right to left to construct the sub-heap. Each position of the array has a root node of a sub-heap, and sink() is also applicable to these sub-heaps. If the two child nodes of a node are already in the heap, then calling the sink() method on the node can save them. Combined into a heap. We can skip the sub-heap of size 1, because the sub-heap of size 1 does not require sink(), that is, sinking operation. For sinking and floating operations, please refer to the priority queue article I wrote.
    2. Heap sorting, we construct a heap through the first step. In this heap, the root node is always the node with the maximum value, so we exchange the value of the root node with the last value of the array. In Just use sink() sinking to maintain the structure of the heap.

  • Specific code implementation:

public class PQSort{
	public static void main(String[] args){
		int[] a = {9,1,7,5,3,9,12,56,21,45};
		sort(a);
		for(int i=0;i<a.length system.out.print public int for>=0;k--){
				sink(a,k,N);
			}
			//通过不断把堆中最大值放到数组的后面来排序
			while(N>0){
				exch(a,0,N--);
				sink(a,0,N);
			}
	}
	//下沉函数
	private static void sink(int[] a, int i, int n){
		while(2*i+1a[j]) break;
			exch(a,i,j);
			i=j;
		}
	}
	//交换函数
	private static void exch(int[] a, int i, int j){
		int temp = a[i];
		a[i] = a[j];
		a[j] = temp;
	}
}</a.length>

Running result:

What is heap sort in java? Introduction to heap sort

The above is the detailed content of What is heap sort in java? Introduction to heap sort. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete