选择排序
-
代码
<script> let arr = [1, 4, 6, 8, -2]; console.log(arr); for (let i = 0; i < arr.length; i++) { for (let j = i; j < arr.length; j++) { if (arr[i] > arr[j + 1]) { let temp = arr[i]; arr[i] = arr[j+1]; arr[j+1] = temp; } } } console.log(arr); </script>
-
运行效果
冒泡排序
-
代码
<script> let arr = [5, 9, -4, 3, 2]; console.log(arr); for (let i = 0; i < arr.length; i++) { for (let j = 0; j < arr.length - i; j++) { if (arr[j] > arr[j + 1]) { let temp = arr[j]; arr[j] = arr[j+1]; arr[j+1] = temp; } } } console.log(arr); </script>
-
运行效果