Home >Web Front-end >JS Tutorial >JS implements simple sorting
This article mainly shares with you JS to implement simple sorting, including bubble sorting and selection sorting. I hope it can help everyone.
1. Bubble sorting: compare two adjacent elements in sequence, exchange sizes
var arr = [3, 5, 15, 36, 36, 27, 2, 38]; //冒泡排序 function bubbleSort(arr) { var len = arr.length; for (var i = 0; i < len - 1; i++) { for (var j = 0; j < len - 1 - i; j++) { if (arr[j] > arr[j + 1]) { var temp = arr[j + 1]; arr[j + 1] = arr[j]; arr[j] = temp; } } } //return arr; } bubbleSort(arr); for (var i = 0; i < arr.length; i++) { alert(arr[i]); }
2. Selection sorting: select the most valuable element, Put it first, and then continue to select the best value among the remaining elements.
//选择排序 var arr = [3, 5, 15, 36, 36, 27, 2, 38]; function selectSort(arr) { var len = arr.length; var minIndex, temp; for (var i = 0; i < len - 1; i++) { minIndex = i; for (var j = i + 1; j < len; j++) { //寻找最小的值,保存索引 if (arr[j] < arr[minIndex]) { minIndex = j; } } temp = arr[i]; arr[i] = arr[minIndex]; arr[minIndex] = temp; } } selectSort(arr); for (var i = 0; i < arr.length; i++) { alert(arr[i]); }
Related recommendations:
php simple sorting bubble sort and selection sort
The above is the detailed content of JS implements simple sorting. For more information, please follow other related articles on the PHP Chinese website!