Two sorting methods commonly used in js (bubble and selection)

Two sorting methods commonly used in js (bubble and selection)

Bubble Sort

insert image description here
var arr1 = [12,35,48,10,26];
var a;
function fn(arr){ for(var x=0;x<arr.length;x++){ //The outer loop controls the total number of exchanges Number for(var y=0;y<arr.length-x-1;y++){ //The inner loop compares the current position with the next one if(arr[y]>arr[y+1]){ // If the current number is greater than the last one, then exchange the position a = arr[y]; arr[y] = arr[y+1]; arr[y+1] = a; } } } return arr; } console.log(fn (arr1));














selection sort

insert image description here
var arr1 = [12,35,48,10,26];
var a;
function fn(arr){ for(var x=0;x<arr.length;x++){ //The outer loop controls the total number of exchanges Number for(var y=x+1;y<arr.length;y++){ //The inner loop performs all comparisons between the xth position and the x position if(arr[x]<arr[y]){ //if If the current number is less than the next digit, the position is exchanged a = arr[x]; arr[x] = arr[y]; arr[y] = a; } } } return arr; } console.log(fn(arr1));














Guess you like

Origin blog.csdn.net/moanuan/article/details/103389215