Bubble sort
Principle: cycle round, compare the current data with the next data, select the maximum or minimum value of each cycle;
let arr = [1.3.2.4.7.6.8.5]; // bubble sort for(let I = 0; i < arr.length; i++){ for( let j = 0; j < arr.length-i; j++){ if( arr[j] < arr[j+1]){ let tmp = arr[j]; arr[j] = arr[j+1]; arr[j+1] = tmp; }}}Copy the code
Selection sort
Principle: Put the smallest or largest number in the first position of the current loop by comparison, until all numbers become ordered, the last number does not need to be sorted, so loop.length-1 is ok
let arr = [1.2.5.8.3];
for( let i = 0; i < arr.length- 1; i++){ for( let j = i+1; j < arr.length; j++){ if( arr[i] < arr[j]){ lettmp = arr[i]; arr[i] = arr[j]; arr[j] = tmp; }}}console.log(arr);Copy the code
reverse
Principle: The array before and after the corresponding part of a data exchange, when the array length is odd numbers in the middle of the exchange is not involved
let arr = [3.7.85.3.9.4.0];
let length = parseInt(arr.length/2); for(let i = 0; i < length; i++){ let temp = arr[i]; arr[i] = arr[arr.length- 1-i]; arr[arr.length- 1-i] = temp; } console.log(arr);Copy the code