冒泡排序就是从数列的第0个数开始对比,若a[i] > a[i+1], 则调换i和i+1的顺序,比较n-1次。最后形成了小的数在前,大的数在后。
function bubbleSort(arr) {
for (let len = 0; len < arr.length - 1; len++) {
for (let i = len; i > 0; i--) {
if (arr[i] > arr[i + 1]) {
[arr[i], arr[i + 1]] = [arr[i + 1], arr[i]]
}
}
}
// arr = arr.sort(function (x, y) { return x - y})
return arr
}
// test
let arr = [8, 1, 2, 10, 3, 7, 9, 4, 5, 6];
let sortArr = bubbleSort(arr)
console.log(sortArr, '<=== bubbleSort')
快速排序就是从目标数组中取一个标识值出来,将数组中的每一项都与这个值做比较,大的放一边,小的放一边;再将左边和右边的子数组分别再取一个标识出来做比较,以此类推递归,直到子数组长度为1.
Array.prototype.quickSort = function (fn) {
const isFn = (f) => {
if (f === undefined) return 0;
else if (typeof f !== 'function') {
throw new Error(`fn must be function, but got a ${typeof f}`);
}
const compare = f(3, 1);
return isNaN(compare) ? 0 : (compare > 0 ? 1 : -1);
};
const small2big = isFn(fn);
const quick = (arr) => {
if (arr.length <= 1) return arr;
if (!small2big) return arr; // 0: 不排序 1: 升序 -1: 降序
const mid = Math.floor(arr.length / 2);
const reference = arr.splice(mid, 1)[0];
const left = [], right = [];
arr.forEach((item) => {
if (small2big > 0) {
if (item > reference) {
right.push(item);
} else {
left.push(item);
}
} else {
if (item < reference) {
right.push(item);
} else {
left.push(item);
}
}
});
return quick(left).concat(reference, quick(right));
};
return quick(this);
}
const c = [1, 3, 6, 7, 8, 3, 4, 2, 5, 7, 8, 9, 6, 4, 3, 2];
const d = [1, 5, 3, 6, 7];
console.log(c.quickSort(function (a, b) { return b - a; }), '排序后 vs 排序前', c);
console.log(d.quickSort(), '排序后 vs 排序前', d);
翻译题目:【士可杀不可辱!】
平常答:You can kill me, but you can not fuck me.
优秀答:A scholar prefers death to humiliation.
我答:Shi ke sha, bu ke ru.