实现排序 js
数组排序方法
JavaScript 提供了 Array.prototype.sort() 方法对数组进行原地排序。默认情况下,该方法将元素转换为字符串并按 Unicode 码点排序。
const fruits = ['banana', 'apple', 'orange'];
fruits.sort();
console.log(fruits); // ['apple', 'banana', 'orange']
数字排序
默认的 sort() 方法对数字排序可能产生意外结果,需传入比较函数。

const numbers = [40, 100, 1, 5, 25];
numbers.sort((a, b) => a - b); // 升序
console.log(numbers); // [1, 5, 25, 40, 100]
numbers.sort((a, b) => b - a); // 降序
console.log(numbers); // [100, 40, 25, 5, 1]
对象属性排序
通过比较函数可基于对象属性排序。

const users = [
{ name: 'Alice', age: 25 },
{ name: 'Bob', age: 30 },
{ name: 'Charlie', age: 20 }
];
users.sort((a, b) => a.age - b.age); // 按年龄升序
console.log(users); // Charlie(20), Alice(25), Bob(30)
稳定排序
ES2019 规定 sort() 必须为稳定排序(相同键值保持原始顺序)。
const data = [
{ value: 2, order: 1 },
{ value: 1, order: 2 },
{ value: 2, order: 3 }
];
data.sort((a, b) => a.value - b.value);
// 保证 value=2 的两个对象保持原始顺序
自定义排序逻辑
比较函数可返回任意负数、零或正数实现复杂排序。
const items = ['March', 'Jan', 'Feb', 'Dec'];
items.sort((a, b) => a.localeCompare(b)); // 按字母顺序
console.log(items); // ['Dec', 'Feb', 'Jan', 'March']
性能注意事项
sort() 的时间复杂度通常为 O(n log n),但具体实现依赖浏览器引擎。大规模数据排序建议考虑 Web Worker 或分治策略。






