js实现sort
实现 JavaScript 的排序功能
JavaScript 提供了 Array.prototype.sort() 方法来实现数组排序。该方法默认将元素转换为字符串后按 Unicode 码点排序,但可以通过自定义比较函数实现更复杂的排序逻辑。
基本用法(默认排序)
默认情况下,sort() 方法会将数组元素转换为字符串后排序:
const fruits = ['banana', 'apple', 'orange', 'grape'];
fruits.sort();
console.log(fruits); // ['apple', 'banana', 'grape', 'orange']
对于数字数组,默认排序可能不符合预期:
const numbers = [10, 2, 5, 1, 9];
numbers.sort();
console.log(numbers); // [1, 10, 2, 5, 9](按字符串比较)
自定义比较函数
要实现数字排序或其他自定义排序,需要提供比较函数:
const numbers = [10, 2, 5, 1, 9];
numbers.sort((a, b) => a - b); // 升序
console.log(numbers); // [1, 2, 5, 9, 10]
numbers.sort((a, b) => b - a); // 降序
console.log(numbers); // [10, 9, 5, 2, 1]
比较函数应返回:

- 负数:
a应排在b前面 - 正数:
b应排在a前面 - 0:顺序不变
对象数组排序
对于对象数组,可以基于对象属性排序:
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);
// [
// { name: 'Charlie', age: 20 },
// { name: 'Alice', age: 25 },
// { name: 'Bob', age: 30 }
// ]
字符串排序(区分大小写)
默认的字符串排序区分大小写(大写字母排在小写字母前面):
const words = ['apple', 'Banana', 'cherry', 'Date'];
words.sort();
console.log(words); // ['Banana', 'Date', 'apple', 'cherry']
要实现不区分大小写的排序:

words.sort((a, b) => a.localeCompare(b, undefined, { sensitivity: 'base' }));
console.log(words); // ['apple', 'Banana', 'cherry', 'Date']
稳定排序
从 ES2019 开始,sort() 被要求是稳定排序(相同值的元素保持原始相对顺序):
const data = [
{ value: 1, order: 1 },
{ value: 2, order: 2 },
{ value: 1, order: 3 }
];
data.sort((a, b) => a.value - b.value);
console.log(data);
// [
// { value: 1, order: 1 },
// { value: 1, order: 3 },
// { value: 2, order: 2 }
// ]
性能注意事项
sort() 的时间复杂度取决于具体实现,现代浏览器通常使用 TimSort 或类似算法,平均时间复杂度为 O(n log n)。对于大型数组,可能需要考虑性能优化。
实现自定义排序算法
虽然通常建议使用内置的 sort() 方法,但了解排序算法实现也有价值。以下是快速排序的 JavaScript 实现:
function quickSort(arr) {
if (arr.length <= 1) return arr;
const pivot = arr[0];
const left = [];
const right = [];
for (let i = 1; i < arr.length; i++) {
arr[i] < pivot ? left.push(arr[i]) : right.push(arr[i]);
}
return [...quickSort(left), pivot, ...quickSort(right)];
}
const nums = [5, 3, 8, 4, 2];
console.log(quickSort(nums)); // [2, 3, 4, 5, 8]






