Selection sort is also a simple and intuitive sorting algorithm. What this article brings to you is about the js sorting algorithm: the algorithm principle and code implementation of js selection sorting. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
Initially find the smallest (large) element in the sequence and place it at the beginning of the sequence as the sorted sequence.
Then continue to find the smallest (large) element from the remaining unsorted elements and put it at the end of the sorted sequence.
And so on until all elements are sorted.
Note: The difference between selection sort and bubble sort: Bubble sort sequentially exchanges the positions of two adjacent elements with illegal order, thereby placing the current smallest (large) element into Suitable location. Selection sort remembers the position of the current smallest (large) element during each traversal, and finally only needs one exchange operation to place it in the appropriate position.
Selection sort implementation array sorting from small to large
function mintomax(par){ for(var i=0; i<par.length-1; i++){ for(var j=i+1; j<par.length; j++){ if(par[j]<par[i]){ var temp; temp=par[j]; par[j]=par[i]; par[i]=temp; } } } return par; } var arr = [11, 2, 3, 445, 7, 32, 71, 8, 94]; console.log(mintomax(arr));
Selection sorting implements sorting the array from large to small
function maxtomin(par){ for(var i=0; i<par.length-1; i++){ for(var j=i+1; j<par.length; j++){ if(par[j]>par[i]){ var temp; temp=par[j]; par[j]=par[i]; par[i]=temp; } } } return par; } var arr = [11, 2, 3, 445, 7, 32, 71, 8, 94]; console.log(maxtomin(arr));
The result after sorting the above code
Related recommendations:
JS Bubble Sort Selection Sort and Insertion Sort Example Analysis
php Array sorting method sharing (bubble sort, selection sort)
Detailed explanation of selection sort in JavaScript
The above is the detailed content of js sorting algorithm: algorithm principle and code implementation of js selection sorting. For more information, please follow other related articles on the PHP Chinese website!