Java Max heap __ algorithm

Source: Internet
Author: User
public class Heapbig {public static void main (string[] args) {//TODO automatically generated method stubs int[] A = {10, 8, 11, 8, 14, 9, 4,
		1, 17};
		Heapbig HB = new Heapbig ();
		Hb.heapsort (a);
	for (int x:a) System.out.print (x + ""); For subscript I, its parent node is labeled (i + 1)/2-1, the left child node is labeled I * 2 + 1, the right child node is labeled I * 2 + 2//maintenance maximum heap public void maxheapify (int[] A, int i
		, int length) {int L = left (i);
		int r = Right (i);
		int Max;
		if (l < length && a[l] > A[i]) {max = L;
		else {max = i;
		} if (r < length && A[r] > A[max]) {max = R;
			} if (max!= i) {swap (A, I, max); The value of node Max becomes the value of the smaller original node I, so the subtree with node Max as the root node may violate the nature of the maximum heap//node I becomes node Max, so recursively calls Maxheapify (A, max, length) maxheapify
		, length);
	}///Find the Child left node ordinal of node I public int left (int i) {return I * 2 + 1;
	//Find node I's Sub right node ordinal public int right (int i) {return I * 2 + 2;
		public void swap (int a[], int i, int j) {int temp = A[i];
		A[i] = A[j];
	A[J] = temp; //Establish maximum heap public void Buildmaxheap (int[] a) {for (int i = A.LENGTH/2 + 1; I >= 0; i) {maxheapify (A, I, a.length); The maximum element of the heap sort///whole array is always the first in the largest heap, that is, a[0]. At this point, if we take the first element, put it in the last position in the array, and then maintain the maximum heap maxheapify for the first element, and so on, we can complete the order of the entire array public void Heapsort (int[] a) {//
		First, the maximum heap is established, and the first element is the maximum value buildmaxheap (a);
		int length = A.length; 
			for (int i = a.length-1 i >= 1;-i) {swap (A, I, 0);//move the first largest element to the back, and ignore it in the process of maxheapify by reducing length--length;
		Maxheapify (A, 0, length);
 }
	}
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.