Array sorting
1, bubble sort is the most commonly used and easiest to understand the sorting method (a nested loop compare each time the size according to set conditions to exchange position).
1 functionbubblesort (ary) {2 for(vari = 0; i < ary.length-1; i++) {3 for(varj = 0; J < ary.length-i-1; J + +) {4 if(Ary[j] > ary[j + 1]) {5 vartemp =Ary[j];6ARY[J] = ary[j + 1];7Ary[j + 1] =temp;8 }9 }Ten } One}
2. Insert Sort by each comparison and then insert a larger or smaller value into the position of the previous number, the value at the current position is subscript backward one
1 functionInsertionsort () {2 if(Arr.length > 1) {3 vartemp =NULL;4 for(vari = 1; i < arr.length; i++) {5 if(arr[i]<arr[i-1]) {6temp =Arr[i];7 varp = i-1;8 while(P >= 0 && arr[p] >temp) {9Arr[p + 1] =Arr[p];Tenp--; One } AArr[p + 1] =temp; - } - } the } -}
3, Quick sort quick Sort is also called the binary sorting, the array is decomposed by recursion, and then all the decomposed arrays are spliced by Concat .
1 functionquicksort (Tarr) {2 if(tarr.length>1) {3 varCenterindex = parseint (tarr.length/2);4 varLarr=tarr.splice (centerindex,1);5 varleft=[],right=[];6 for(vari=0;i<tarr.length;i++){7 if(tarr[i]<larr[0]) {8 Left.push (Tarr[i]);9}Else{Ten Right.push (Tarr[i]); One } A } - returnfnkspx (left). Concat (Larr,fnkspx (right)); -}Else{ the returnTarr; - } -}
JavaScript Learning notes Array sorting