Heap Sort Java Implementation

Source: Internet
Author: User

 PackageKpp.sort;/**@authorKPP **/ Public classHeapsort { Public Static voidMain (string[] args) {//TODO auto-generated Method Stub        intArray[] = {49,38,65,97,176,213,227,49,78,34,12,164,11,18,1};        Heapsort (array);  for(intK:array)        {System.out.println (k); }    }    /*** Heap Sort *@paramArray*/     Public Static voidHeapsort (int[] Array) {        //Building the initial heapbuildheap (array); intn =Array.Length;  for(inti=n-1;i>=1;i--){            //swap heap top element and last unordered elementSwap (array,0, i); //re-adjust the rest of the heapAdjustheap (array,0, i); }    }        /*** Build a heap *@paramArray*/     Public Static voidBuildheap (int[] Array) {        intn = array.length;//the number of elements in the array         for(inti=n/2-1;i>=0;i--) Adjustheap (array,i,n); }    /*** Adjustment Heap *@paramA *@paramCurrent Element *@paramend current need to adjust the last leaf node subscript of the heap*/     Public Static voidAdjustheap (int[] A,intCurrentintend) {        intleft = 2*current+1;//The subscript of the left child (if present)        intRight =2*current+2;//The subscript of the left child (if present)        intlargest = 0;//looking for the subscript of the maximum node in 3 nodes        if(Left<end && a[left]>A[current]) largest=Left ; Elselargest=Current ; if(Right<end && a[right]>A[largest]) largest=Right ; if(largest!=Current )            {swap (a,largest,current);                        Adjustheap (A,largest,end); }        }    /*** Heap top element and last unordered element interchange *@paramArray *@paramI *@paramJ*/     Public Static voidSwapint[] Array,intIintj) {        intTemp =0; Temp=Array[i]; Array[i]=Array[j]; ARRAY[J]=temp; }}

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.