Heap Sort Java Implementation

Source: Internet
Author: User

 Packagepractice;ImportEdu.princeton.cs.algs4.StdRandom; Public classTestmain { Public Static voidMain (string[] args) {int[] A =New int[20];  for(inti = 0; i < a.length; i++) {            inttemp = (int) (Stdrandom.random () *100); A[i]=temp;        } heapsrot.sort (a);  for(inti = 1; i < a.length; i++) {//only from a[1] Start rowSystem.out.print (a[i]+ "");    } System.out.println (); }}classheapsrot{ Public Static voidSortint[] a) {intp =a.length;  for(intK = P/2; K >= 1; k--) {//because nodes without child elements are not processed, only half of the elements are processedSink (A, k, p);//from bottom to top all (excluding nodes without child elements), node sinks once, entire array is stacked in order}//why not plug in and float like a priority queue, because it's quick to 20%~30%         while(P > 1) {//and the priority queue pops up the largest element and deletes the action, rather than deleting the largest element to the endExch (A, 1,--p);//move the first one to the endSink (A, 1, p);//will be replaced by sinking down        }    }    /** Sinking*/    Private Static voidSinkint[] A,intKintP) {//Compare elements to sub-elements, smaller than sub-elements, and the larger of the two, swapping positions         while((2*k + 1) < P && ((A[k] < A[2*k + 1]) | | (A[k] < a[2*K] )) {if(A[2*k + 1] > A[2*k]) {Exch (A, K, 2*k + 1); k = 2*k + 1; } Else{Exch (A, k, 2*k); k =K;} }    }    /** Exchange*/    Private Static voidExch (int[] A,intIintj) {intt =A[i]; A[i]=A[j]; A[J]=T; }}

Algorithm Animation Demo

Http://www.cs.usfca.edu/~galles/visualization/HeapSort.html

Heap Sort Java Implementation

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.