JS selection sort
The principle is to find the smallest element in the original array and place that element at the top of the array, and then find the smallest element from the remaining elements and place it behind the previous smallest element until the sorting is complete.
Var arr1 =,33,11,23,56,72,78,24,14,58 [2]; Function selectionSort(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]){// find minIndex =j; } } temp=arr[i]; Arr [I]=arr[minIndex]; // arr[minIndex]=temp; } return arr; } document.write(selectionSort(arr1))Copy the code
Bubble sort
Bubble sort: there are n numbers in the array, compare each adjacent two numbers, if the former is greater than the latter, the two numbers swap places, the first round can choose the largest number in the last; Then after an n-1 round (length-1 of the array), we are done sorting all the numbers.”
function BubbleSort(array) { var length = array.length; for (var i = length - 1; i > 0; Var j = 0; var j = 0; j < i; If (array[j] > array[j+1]) {var temp = array[j]; array[j] = array[j+1]; array[j+1] = temp; } } } return array; } var arr = [10,9,8,7,7,6,5,11,3]; var result = BubbleSort(arr); console.log(result);Copy the code