Array Ordering of JS
Give an array of numbers that do not need to let the write bubble sort:
Analysis: Bubble sort refers to the number of the first item compared to the second item, the first big words of the two swap positions, if the second big words will be the same position;
After comparing the second third item, the comparison result repeats the previous step; (Inner for Loop)
The first comparison is done at the beginning of the second item in the previous link; (Outer for Loop)
Only until the end of the last second item is completed;
An example of an array of arr = [3,56,4,1,34,78,23,59,66,42];
Bubble sort function Arrsort (arr) {var len = arr.length;for (var i = 0; I <len; i++) {//determines the number of cycles required for (var j = 0; j < Len-1-i; J + +) {if (arr[j]>arr[j+1]) {//adjacent two items for comparison var nu = arr[j+1];arr[j+1] = arr[j];arr[j]= nu;}}} Console.log (arr);} Arrsort (arr);
But this two for loop is quite a memory-intensive operation if the amount of data is large, because each time the for loop is completed to find a maximum number in the last position,
The outer loop does not have a coarse cycle to the last few to re-cycle, in order to save the number of cycles in each of the last time for the loop to change the location of the mark;
2. Improved bubble sorting:
function ArrSort2 (arr) {var i = Arr.length-1;while (i>0) {console.log (i)///Here the index of each data position of arr (minus the first item 0), var pos = 0 0;for (Var j=0;j<i;j++) {if (arr[j]>arr[j+1]) {Pos=j;var Nu = arr[j+1];arr[j+1] = arr[j];arr[j]= nu Each time the loop is positioned; }} i=pos;//the location of the last interchange;} console.log (arr); } arrSort2 (arr);
Save some unnecessary loops and increase the speed of operation!
The array bubble sort of JS interview frequently test