ImportJava.io.*;ImportJava.util.*; Public classmain{ Public Static voidMain (String args[]) {Scanner cin=NewScanner (system.in); //arraylist<string> list = new arraylist<string> (); //Scanner scan = new Scanner (system.in);//get another format for keyboard input int[] list={};//if the external declaration is not static initialized, then the array inside the while is changed to a local variable, which cannot be retrieved outside the loop . while(Cin.hasnextint ()) {ints=Cin.nextint (); List=New int[S];//declaring array length for(intI=0;i<list.length;++i) {//Assigning a value to an arrayList[i] =Cin.nextint (); } Break; } //The following is a concrete algorithm, heap sequencing (non-recursive)//1. Initializing the heapList =confirm (List,list.length); //2. Start heap sequencing for(intj=list.length-1;j>=0;--j) { inttmp=List[j]; LIST[J]=list[0]; list[0]=tmp; List= Confirm (LIST,J);//The last one doesn't need to be compared } for(inti=0;i<list.length;++i) {System.out.println (list[i]); } }//methods for initializing heaps Public Static int[] Init (int[] list,intcycnum) { for(inti=cycnum-1;i>=0;--i) { if(2*i+1>cycnum-1){ Continue;//to the bottom leaf node, jump out of the loop } intmax=0;//record the larger of the left and right nodes, the size of the value intkey=0;//record the size of the key if(2*i+2>cycnum-1) {Max=list[2*i+1]; Key=2*i+1; }Else{Max=LIST[2*I+1]>LIST[2*I+2]? List[2*i+1]:list[2*i+2]; Key=LIST[2*I+1]>LIST[2*I+2]? 2*i+1:2*i+2; } if(max>List[i]) {List[key]=List[i]; List[i]=Max; } } returnlist;} Public Static int[] Confirm (int[] list,intcycnum) { for(intj=0;j<=cycnum;++j) {List= init (list,cycnum);//Call the heap method, just call for loop, no recursion if(List = =init (list,cycnum)) { Break; } } returnlist;}}
Write your own algorithm---the non-recursive traversal of the Java heap