js sort 实现
排序方法概述
JavaScript中的Array.prototype.sort()方法用于对数组元素进行排序。默认情况下,sort()方法将数组元素转换为字符串,并按照Unicode码点顺序进行排序。对于数字排序,这可能导致不符合预期的结果,因此通常需要自定义比较函数。
默认排序行为
默认的sort()方法将元素视为字符串进行排序:
const fruits = ['banana', 'apple', 'orange'];
fruits.sort();
console.log(fruits); // ['apple', 'banana', 'orange']
对于数字数组,默认排序可能产生错误结果:
const numbers = [10, 5, 100];
numbers.sort();
console.log(numbers); // [10, 100, 5] (按字符串比较)
自定义比较函数
为了正确排序数字或其他复杂类型,需要提供比较函数。比较函数接收两个参数(通常称为a和b),并返回以下值:
- 负数:a应排在b前面
- 正数:b应排在a前面
- 0:保持原有顺序
数字升序排序:
const numbers = [10, 5, 100];
numbers.sort((a, b) => a - b);
console.log(numbers); // [5, 10, 100]
数字降序排序:
const numbers = [10, 5, 100];
numbers.sort((a, b) => b - a);
console.log(numbers); // [100, 10, 5]
对象数组排序
对于对象数组,可以根据对象的某个属性进行排序:
const users = [
{ name: 'John', age: 25 },
{ name: 'Alice', age: 20 },
{ name: 'Bob', age: 30 }
];
// 按年龄升序
users.sort((a, b) => a.age - b.age);
console.log(users);
// [
// { name: 'Alice', age: 20 },
// { name: 'John', age: 25 },
// { name: 'Bob', age: 30 }
// ]
字符串排序注意事项
对于字符串排序,默认行为是区分大小写的:
const words = ['apple', 'Banana', 'orange'];
words.sort();
console.log(words); // ['Banana', 'apple', 'orange']
要进行不区分大小写的排序:
const words = ['apple', 'Banana', 'orange'];
words.sort((a, b) => a.localeCompare(b, undefined, { sensitivity: 'base' }));
console.log(words); // ['apple', 'Banana', 'orange']
稳定排序
从ES2019开始,JavaScript要求sort()方法实现稳定排序(相等元素保持原有顺序):
const data = [
{ name: 'Alice', age: 25 },
{ name: 'Bob', age: 30 },
{ name: 'John', age: 25 }
];
// 按年龄排序,相同年龄保持原顺序
data.sort((a, b) => a.age - b.age);
console.log(data);
// [
// { name: 'Alice', age: 25 },
// { name: 'John', age: 25 },
// { name: 'Bob', age: 30 }
// ]
性能考虑
sort()方法的时间复杂度和空间复杂度取决于JavaScript引擎的实现。现代浏览器通常使用高效的排序算法(如Timsort),时间复杂度为O(n log n)的最坏情况。

对于大型数组,频繁调用比较函数可能影响性能。可以考虑预先计算排序键或使用更高效的数据结构。






