模拟js数组中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));