In fact, the reverse output of the array is relatively simple, because the array is already ordered, so as long as the loop and then press into a new array.
Perhaps you would write this:
function Backsort (arr) { var finalarr = []; for (var i = arr.length-1; I >= 0; I--) { finalarr.push (arr[i]); } return Finalarr;} Console.log (Backsort ([1,2,3,4,5]));
Java, which does not have an array of such push operations, can be written like this:
Public voidBacksort () {Finalarr=New int[0]; for(inti = numarr.length-1; I >= 0; I--) {Finalarr=Joinnewarr (Finalarr, numarr[i]); } Numarr=Finalarr; Finalarr=NULL;} Public int[] Joinnewarr (int[] arr,intnum) { int[] Midarr =New int[Arr.length + 1]; if(Arr.length = = 0) {midarr[0] =num; }Else{system.arraycopy (arr,0, Midarr, 0, arr.length); Midarr[midarr.length-1] =num; } returnMidarr;}
The idea is to loop forward from the back, then press into the new array to print out. That's right!
However, through yesterday's analysis of the quick sort, we understood the idea that each cycle was checked at the same time through the first two directions. This means that you cycle through the first two values, the number of cycles required for this to halve the wood has, greatly improved the efficiency ~
So we introduce this idea, for this sequential array of flashback output can reduce nearly half the number of cycles, it is wonderful!
Come and feel it:
function Quicktobacksort (arr) { var firstsub = 0; var lastsub = arr.length-1; while (Firstsub < lastsub) { = arr[firstsub] + arr[lastsub]; = Arr[firstsub]- arr[lastsub]; = Arr[firstsub]- arr[lastsub]; Firstsub+ +; Lastsub--; } return arr;}
And for Java, do not create a new array frequently, the program to run the steps directly reduce the huge number of wood there ah!
Public voidQuickbacksort () {intFirstsub = 0; intLastsub = numarr.length-1; while(Firstsub <lastsub) { while(Firstsub <lastsub) {Numarr[firstsub]= Numarr[firstsub] +Numarr[lastsub]; Numarr[lastsub]= Numarr[firstsub]-Numarr[lastsub]; Numarr[firstsub]= Numarr[firstsub]-Numarr[lastsub]; Firstsub++; Lastsub--; } }}
Reverse output of an ascending or descending array