【JS数据算法】排序

基于sort

let a = [1, 6, 4, 33, 9, 7, 2]
console.log(a.sort((a, b) => a - b))

冒泡排序需要用到数字交换方法

// 交换方法1
function swap1(a,b){
	let c = a;
	a = b;
	b = a;
}

// 交换方法2
function swap2(a,b){
	[a,b] = [b,a]
}

// 交换方法3
function swap3(a,b){
	a = a + b;
	b = a - b;
	a = a - b;
}

冒泡排序

  1. 从数组第一项开始,每一项与下一项进行比较,如果大于下一项则互换位置,换完一轮则第一项是最小的一项
  2. 再从第二项开始比较,以此类推
  3. 因此一共需要比较数组长度-1轮,每轮需要比较数组长度-1再减去已比较轮数
// 实现数组中的数字交换
function swap(arr,i,j){
	arr[i] = arr[i] + arr[j];
	arr[j] = arr[i] - arr[j];
	arr[i] = arr[i] - arr[j];
	return arr;
}

// 冒泡排序
Array.prototype.bubble = function bubble() {
    let that = this,
        flag = false;
    for (let i = 0; i < that.length - 1; i++) {
        for (let j = 0; j < that.length - 1 - i; j++) {
            if (that[j] > that[j + 1]) {
                swap(that, j, j + 1);
                flag = true;
            }
        }
        if (!flag) break;
        flag = false;
    }
    return that;
}

let a = [1, 6, 4, 33, 9, 7, 2]
console.log(a.bubble())

插入排序

  1. 先将数组第一项插入新数组
  2. 再将数组每一项新数组中的每一项进行比较
  3. 如果大于则插入比较项之后,反之则插入比较项之前
// 冒泡排序
Array.prototype.insert = function insert() {
    let that = this,
        arr = [];
    arr.push(that[0]);
    for (let i = 1; i < that.length; i++) {
        let A = that[i];
        for (let j = that.length - 1; j >= 0; j--) {
            let B = arr[j];
            if (A > B) {
                arr.splice(j + 1, 0, A);
                break;
            }
            if (j === 0) {
                arr.unshift(A)
            }
        }
    }
    return arr;
}

let a = [1, 6, 4, 33, 9, 7, 2]
console.log(a.insert())

快速排序(二分法)

  1. 找出中间项
  2. 每一项与中间项进行比较
  3. 如果大于中间项则插入存储大于中间项数值的数组,反之插入存储小于中间项数值的数组
  4. 将每个新数组都进行快速排序(递归)
  5. 最终将左中右三个数组或数值依次拼接
Array.prototype.quick = function quick() {
    let that = this;
    if (that.length <= 1) {
        return that
    }
    let middleIndex = Math.floor(that.length / 2),
        middleValue = that.splice(middleIndex, 1)[0],
        arrLeft = [],
        arrRight = [];
    for (let i = 0; i < that.length; i++) {
        let num = that[i];
        num < middleValue ? arrLeft.push(num) : arrRight.push(num);
    }
    return quick.call(arrLeft).concat(middleValue, quick.call(arrRight));
}

let a = [1, 6, 4, 33, 9, 7, 2]
console.log(a.insert())
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值