<script>
function quicksort(arr) {
//4.判断数组的长度,如果数组的长度小于1 停止执行;
if (arr.length <= 1) {
return arr;
}
//1.找到数组的中间值(向下取整或者向上取整都可以,这里向下取整),并将原数组中的中间值去掉
let middleIndex = Math.floor(arr.length / 2);
let middleValue = arr.splice(middleIndex, 1);
//2.创建左右的新数组,大于中间数的放在右边,反之左边
let arrLeft = [],
arrRight = [];
for (let i = 0; i < arr.length; i++) {
let temp = arr[i];
temp < middleValue ? arrLeft.push(temp) : arrRight.push(temp);
}
//3.利用函数的递归,并且concat拼接数组
return quicksort(arrLeft).concat(middleValue, quicksort(arrRight));
}
console.log(quicksort([5, 2, 6, 723, 234, 7, 9, 89, 456, 23, 4, 213, 42, 35, 3, 654, 67, 56, 7, 32, 4, 234, ]));
</script>
选择排序法
function selsetSort(arr) {
var len = arr.length;
var index;
for (var i = 0; i < len - 1; i++) {
index = i;
for (var j = i + 1; j < len; j++) {
if (arr[index] > arr[j]) { //寻找最小值
index = j; //保存最小值的索引
}
}
if (index != i) {
var temp = arr[i];
arr[i] = arr[index];
arr[index] = temp;
}
}
return arr;
}
冒泡排序法
function selsetSort(arr) {
let num = 0;
for (let i = 0; i < arr.length; i++) {
for (let j = 0; j < arr.length - i; j++) {
if (arr[j] > arr[j + 1]) {
num = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = num;
}
}
}
return arr;
}
console.log(selsetSort(arr));