1. The sort () method
Let a =,48,3 [1] let b = c = a.c,3,6 [28] let oncat (b) the console. The log (c) / / c.s. ort,48,3,28,3,6 [1] ((a, b) = > {return a - b }) console.log(c) //[1,3,3,6,28,48]Copy the code
2. Bubble sort
- Compare adjacent elements. The first big one will switch places.
- Do the same thing for each pair of adjacent elements, from the first pair to the last pair, and the last element will be the largest.
- Repeat these steps for all elements except the last one.
- Keep repeating the above steps for fewer and fewer elements at a time until there are no more pairs to compare.
Let a=[1,9,33,2,5,34,23,98,14] function arrSort(arr){let len = arr.length; for(let i = 0; i<len-1; i++){ for(let j = 0; j<len-1-i; j++){ if(arr[j]>arr[j+1]){ let temp = arr[j]; arr[j] = arr[j+1]; arr[j+1] = temp; } } } return arr } arrSort(a) //[1, 2, 5, 9, 14, 23, 33, 34, 98]Copy the code
3. Select sort
- First find the smallest (largest) element in the unsorted sequence and store it at the beginning of the sorted sequence.
- Find the smallest (largest) element from the remaining unsorted elements and place it at the end of the sorted sequence
- Repeat the second step until all elements are sorted.
Let a=[1,9,33,2,5,34,23,98,14] function selectSort(arr){let len = arr.length let minIndex,temp for(let I = 0; i<len-1; i++){ minIndex = i; for(let j = i+1; j<len; j++){ if(arr[j]<arr[minIndex]){ minIndex = j; } } temp = arr[i]; arr[i] = arr[minIndex]; arr[minIndex] = temp; } return arr; }Copy the code