This time I will bring you a summary of JS implementation of sorting methods. What are the precautions for JS implementation of sorting? . The following is a practical case, let's take a look.
function Bubble(arr){ var temp; for(var i=0;i<arr.length-1;i++){ for(var j=i+1;j<arr.length;j++){ if(arr[i]>arr[j]){ temp=arr[i]; arr[i]=arr[j]; arr[j]=temp; } } } return arr; } console.log(Bubble([2,5,1,0,6,2])) //[0,1,2,2,5,6]
function selctor(arr){ var min; for(var i=0;i<arr.length-1;i++){ min=i; //依次找到为最小值的索引 for(var j=i+1;j<arr.length;j++){ if(arr[min]>arr[j]){ min=j; } } //如果最小值不在当前位置上 就交换到位置i if(min!=i){ swap(arr,min,i) } } return arr } function swap(arr,index1,index2) { var temp=arr[index1]; arr[index1]=arr[index2]; arr[index2]=temp; }
Insertion sort
function insert(arr){ var j,key; for(var i=1;i<arr.length;i++){ j=i; key=arr[i]; while(--j>-1){ if(arr[j]>key) { arr[j + 1] = arr[j]; }else{ break; } } arr[j+1]=key; } return arr }
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the PHP Chinese website!
Recommended reading:
Detailed explanation of using vuex Actions
##Detailed explanation of jQuery implementation of timer function
The above is the detailed content of Summary of sorting methods implemented in JS. For more information, please follow other related articles on the PHP Chinese website!