Two methods of js array sorting

1. The principle of bubble sorting
 : compare two adjacent numbers at a time, if it does not meet the rules to exchange positions, one comparison can put the largest or smallest value in the last bit of the array and continue to except the [last bit] Repeat the above process for all elements.

let arr = [22,1,43,12,75,32];
for(let i = 0; i < arr.length - 1; i++){
	for(let j = 0; j < arr.length - 1 - i; j++){
	    if(arr[j] > arr[j+1]){
	        let num = arr[j];
	        arr[j] = arr[j+1];
	        arr[j+1] = num;
	    }
	}    
}
console.log(arr);

 

 2. The principle of selection sorting
 : first find the smallest (largest) element in the unsorted array and store it at the beginning of the array. Then continue to find the smallest (largest) element from the remaining array elements, return to the end of the sorted array and repeat the second step until all elements are sorted

let arr = [22,1,43,12,75,32];
for(let i = 0; i < arr.length; i++){
	for(let j = i + 1; j < arr.length; j++){
		if(arr[i] > arr[j]){
			let num = arr[i];
			arr[i] = arr[j];
			arr[j] = num;
		}
	}
}
console.log(arr);

Original author: Wu Xiaotang

Creation time: 2023.5.19

Guess you like

Origin blog.csdn.net/xiaowude_boke/article/details/130775197