排序算法
冒泡排序
javascript
var sortArray = function (nums) {
const { length } = nums;
for (let i = 0; i < length; i++) {
for (let j = 0; j < length - 1 - i; j++) {
if (nums[j] > nums[j + 1]) {
[nums[j], nums[j + 1]] = [nums[j + 1], nums[j]];
}
}
}
return nums;
};
快速排序
javascript
function quickSort(arr) {
if (arr.length < 2) {
return arr;
}
let left = [];
let right = [];
let middle = arr[0];
for (let i = 1; i < arr.length; i++) {
if (arr[i] < middle) {
left.push(arr[i]);
} else {
right.push(arr[i]);
}
}
return quickSort(left).concat([middle], quickSort(right));
}