模拟js数组中sort排序方法(简单实例)

JavaScript sort() 方法 简介

sort() 方法用于对数组的元素进行排序。

排序顺序可以是字母或数字,并按升序或降序。

默认排序顺序为按字母升序。

引用

JavaScript sort() 方法

模拟sort方法简单实现

实现思路

用从左到右依次类比大小,替换位置的方法实现
类比实现sort方法

实现代码

// 将sortSelf方法挂载到Array原型链上
Array.prototype.sortSelf = function (fun) {
  let for_num = 0;
  let cha_num = 0;
  let time = Date.now();
  const len = this.length;
  if (!fun && this.some((v) => typeof v === "string"))
    fun = (a, b) => (a > b ? 1 : -1);
  else if (!fun) fun = (a, b) => a - b;
  for (let i = 0; i < len - 1; i++) {
    // console.log(`i:::::::::::::::::::::::::::${i}`);
    for (let j = i; j < len - 1; j++) {
      for_num++;
      //   console.log(`j:::::::::::::${j}`);
      //调用函数
      if (fun(this[j], this[j + 1]) > 0) {
        //交换两个变量
        // const temp = this[j];
        // this[j] = this[j + 1];
        // this[j + 1] = temp;
        // es6数组结构新写法
        [this[i],this[j]] = [this[j],this[i]];
      }
    }
  }
  time = Date.now() - time;
  console.log(
    `数组长度:${len},循环次数:${for_num},交换次数:${cha_num},耗时:${time} ms`
  );
  return this;
};

测试结果

测试代码

function testSortSelf(arr) {
  const a1 = arr.sortSelf((a, b) => a - b);
  const a2 = arr.sortSelf((a, b) => b - a);
  const a3 = arr.sortSelf(() => 0.5 - Math.random());
  //   console.log(`从小到大 :::::::::::::: ${a1}`);
  //   console.log(`从大到小 :::::::::::::: ${a2}`);
  //   console.log(`随机排列 :::::::::::::: ${a3}`);
}

function generateMockData(num) {
  const arr = [];
  for (let i = 0; i < num; i++) {
    arr.push(Math.round(Math.random() * num));
  }
  return arr;
}

console.log([2, 1, 3].sortSelf());
console.log(["b", "a", "c"].sortSelf());
testSortSelf(generateMockData(10));
testSortSelf(generateMockData(100));
testSortSelf(generateMockData(1000));
testSortSelf(generateMockData(10000));

测试截图

sort测试

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值