Home >Web Front-end >JS Tutorial >JS array sorting method example analysis
The example in this article describes the JS array sorting method. Share it with everyone for your reference. The details are as follows:
Method 1. Bubble sort
Idea: Compare the first element and the second element in the array in turn. If the first element is greater than the second element, swap position, so two functions are needed: the exchange position function and the comparison function
The number of comparison rounds is the length of the array
var arr=[2,58,49,26,34]; function change(f,s){ var temp=arr[f]; arr[f]=arr[s]; arr[s]=temp; } for(var i=0;i<arr.length;i++){ for(var j=0;j<arr.length-1;j++){ if(arr[j]>arr[j+1]){ change(j,+j+1); } } } alert(arr);
Method 2. Selection sort
Find the minimum value from the array, throw it to the first position of the array, and then from The remaining loop operations in the array
var arr=[2,58,49,26,34]; function change(){ if(arr.length==1){ return arr; } var iMin=arr[0]; var index=0; for(var i=0;i<arr.length;i++){ if(arr[i]<iMin){ iMin=arr[i]; index=i; } } var prev=arr.splice(index,1); return prev.concat(change(arr)); } alert(change(arr));
The above is the analysis of the JS array sorting method. For more related articles, please pay attention to the PHP Chinese website (www.php.cn)!