Heap (array sort by heap)-heap sort

Source: Internet
Author: User
Tags array sort

Sort the arbitrarily populated array in piles, then delete the heap, because the heap is always the largest in the current heap, and according to this feature, you can get an ordered array
(in piles) starts from the last parent node and adjusts downward to the topmost parent node.
(delete heap) delete operation, get the current maximum value

 Public classNode {Private intIData;//is both a keyword and a value     PublicNode (intKey) {//InitializeIdata=key; }     Public intGetKey () {//Access Keywords        returnIData; }     Public voidSetkey (intID) {//Change KeywordsIdata=ID; }}
//Build Heap Public classHeap {PrivateNode[] Heaparray;//array of storage nodes    Private intMaxSize;//Total size    Private intCurrentSize;//the size of the current heap     PublicHeap (intmx) {maxSize=MX;//total size of initializationcurrentsize=0;//initializes the current data size of 0heaparray=NewNode[maxsize]; }    //inserts a node to a specified location     Public voidInsertAt (intIndex,node NewNode) {Heaparray[index]=NewNode; }    //add 1 to the current data item value     Public voidincrementsize () {currentsize++; }    //Delete a data     Publicnode Remove () {node root=heaparray[0]; heaparray[0]=heaparray[--currentsize];//move the last data item to the root//Downward AdjustmentTrickledown (0); returnRoot; }    //Downward Adjustment         Public voidTrickledown (intindex) {            intLargechild;//record a large child nodeNode top=Heaparray[index]; //find the top position             while(INDEX&LT;CURRENTSIZE/2) {//The pointer is to the last layer to stop the loop.                intleftchild=2*index+1;//left dial hand node                intrightchile=leftchild+1;//Right child node                if(Rightchile<currentsize && Heaparray[leftchild].getkey () //have right child nodesLargechild=Rightchile; ElseLargechild=Leftchild; if(Top.getkey () >=heaparray[largechild].getkey ())//The data item to be moved is compared to the maximum value obtained above                     Break; Heaparray[index]=heaparray[largechild];//make big keyword adjustmentsindex=Largechild; }            //last position node Top=heaparray[index]heaparray[index]=top; }    //determines whether the empty     Public BooleanIsEmpty () {returnCurrentsize==0; }    //Show Heap         Public voiddisplayheap () {//in a tree-like form            intnblanks=32;//Control Spaces            intItemsperrow=1;//number of current layers            intcolumn=0;//the number of current layers            intJ=0; String Dots="..............................."; System.out.println (Dots+dots);  while(currentsize>0) {                if(column==0) {                     for(intk=0;k<nblanks;k++) System.out.print (‘ ‘);                } System.out.print (Heaparray[j].getkey ()); if(++j==currentsize)//Print all completed                     Break; if(++column==itemsperrow) {//The current layer finishes printingnblanks/=2; Itemsperrow*=2; Column=0;                System.out.println (); }Else                     for(intk=0;k<nblanks*2-2;k++) System.out.print (‘ ‘); } System.out.println ("\ n" +dots+dots); }         Public voidDisplayarray () { for(intm=0;m<maxsize;m++) System.out.print (Heaparray[m].getkey ()+" ");        System.out.println (); }            }
ImportJava.io.BufferedReader;Importjava.io.IOException;ImportJava.io.InputStreamReader; Public classTest { Public Static voidMain (string[] agrs)throwsioexception{intsize,j; System.out.println ("Enter Number of items:"); Size=getInt (); Heap Theheap=NewHeap (size);  for(j=0;j<size;j++) {//put a random number in an array that is first deposited into the heap            intRandom= (int) (Java.lang.Math.random () *100); Node NewNode=NewNode (random);            Theheap.insertat (J, NewNode);        Theheap.incrementsize (); }        //Showtheheap.displayheap (); //sort the heap (change a filled array into piles of form and then sort)//start adjusting from the last parent node until the root         for(j=size/2-1;j>=0;j--) {Theheap.trickledown (j); } System.out.print ("Heap:");        Theheap.displayheap (); //Sort         for(j=size-1;j>=0;j--) {Node Biggestnode=theheap.remove ();//Remove the largest data itemTheheap.insertat (J, Biggestnode);//into the bottom-down node of the heap's underlying array} System.out.println ("Sorted Array:");                                                            Theheap.displayarray (); }     Public StaticString getString ()throwsioexception{InputStreamReader ISR=NewInputStreamReader (system.in); BufferedReader BR=NewBufferedReader (ISR); returnBr.readline (); }     Public Static CharGetChar ()throwsioexception{returnGetString (). CharAt (0); }     Public Static intGetInt ()throwsioexception{returnInteger.parseint (getString ()); }}

Heap (array sort by heap)-heap sort

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.