usort
usort(array &$array, callable $callback): true
用自定义比较回调对数组就地排序,排序后重建数字索引。
C C23
C23
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static int by_len(const void *a, const void *b) { // qsort 需要比较回调
return (int)strlen(*(const char **)a) - (int)strlen(*(const char **)b);
}
int main(void) {
const char *w[] = {"banana", "fig", "kiwi", "apple"};
size_t n = sizeof w / sizeof w[0];
qsort(w, n, sizeof w[0], by_len);
printf("[");
for (size_t i = 0; i < n; i++) {
printf(i ? ", \"%s\"" : "\"%s\"", w[i]);
}
printf("]\n");
return 0;
}
输出
["fig", "kiwi", "apple", "banana"]
C++ C++26
C++26
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
int main() {
std::vector<std::string> w{"banana", "fig", "kiwi", "apple"};
std::sort(w.begin(), w.end(), [](const std::string &a, const std::string &b) {
return a.size() < b.size(); // 比较器返回 bool 而非 int
});
std::cout << "[";
for (size_t i = 0; i < w.size(); ++i) {
if (i) std::cout << ", ";
std::cout << '"' << w[i] << '"';
}
std::cout << "]\n";
return 0;
}
输出
["fig", "kiwi", "apple", "banana"]
C# v11.0.100
v11.0.100
using System;
using System.Collections.Generic;
var words = new List<string> { "banana", "fig", "kiwi", "apple" };
words.Sort((a, b) => a.Length.CompareTo(b.Length)); // Comparison<T> 委托就地排序
Console.WriteLine("[" + string.Join(", ", words.ConvertAll(w => $"\"{w}\"")) + "]");
输出
["fig", "kiwi", "apple", "banana"]
Go v1.27.4
v1.27.4
package main
import (
"fmt"
"sort"
)
func main() {
words := []string{"banana", "fig", "kiwi", "apple"}
sort.Slice(words, func(i, j int) bool { // 以索引为参数的 less 谓词
return len(words[i]) < len(words[j])
})
fmt.Printf("%q\n", words)
}
输出
["fig" "kiwi" "apple" "banana"]
Java v27.0.1
v27.0.1
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> words = new ArrayList<>(List.of("banana", "fig", "kiwi", "apple"));
words.sort(Comparator.comparingInt(String::length)); // 稳定排序 TimSort
System.out.println(words);
}
}
输出
[fig, kiwi, apple, banana]
JavaScript v26.13.1
v26.13.1
const words = ["banana", "fig", "kiwi", "apple"];
words.sort((a, b) => a.length - b.length); // 数值比较器,而非字符串比较
console.log(words);
输出
[ 'fig', 'kiwi', 'apple', 'banana' ]
PHP v8.6.0
v8.6.0
$words = ["banana", "fig", "kiwi", "apple"];
usort($words, fn($a, $b) => strlen($a) <=> strlen($b)); // 飞船比较符,就地排序
echo json_encode($words);
输出
["fig","kiwi","apple","banana"]
Python v3.15.2
v3.15.2
words = ["banana", "fig", "kiwi", "apple"]
print(sorted(words, key=len)) # key 函数返回排序键,而非比较器
输出
['fig', 'kiwi', 'apple', 'banana']
Rust v1.99.1
v1.99.1
fn main() {
let mut words = vec!["banana", "fig", "kiwi", "apple"];
words.sort_by_key(|w| w.len()); // 按提取的键稳定排序
println!("{:?}", words);
}
输出
["fig", "kiwi", "apple", "banana"]
TypeScript v26.13.1
v26.13.1
const words: string[] = ["banana", "fig", "kiwi", "apple"];
words.sort((a, b) => a.length - b.length); // 数值比较器,而非字符串比较
console.log(words);
输出
[ 'fig', 'kiwi', 'apple', 'banana' ]
语言差异说明
C:比较器返回整数(负/零/正);qsort 不保证稳定。
C++:比较器只返回 bool(「前者应排在后者前」);std::sort 不保证稳定(要稳定用 std::stable_sort)。
C#:Comparison<T> 委托只返回 bool;List<T>.Sort 不保证稳定(C# 的 LINQ OrderBy 稳定)。
Go:sort.Slice 的 less 谓词只返回 bool;不保证稳定(sort.SliceStable 才保证)。
Java:List.sort(TimSort)稳定。
JavaScript:比较器返回整数;sort 原地排序数组。
PHP:回调形态是第一分岔——比较器返回整数(负/零/正);键名行为是本分类教学核心:usort 排序后丢弃原键、重建 0,1,2… 数字索引(要保留键值关联用 uasort)。
Python:回调形态是第一分岔之一——key= 只传「排序键提取函数」,不做两两比较(要比较器风格可用 functools.cmp_to_key 包装);sorted 返回新列表、原列表不动(list.sort 才是原地)。
Rust:sort_by_key 只传排序键提取函数;稳定。
TypeScript:同 JS,sort 原地排序。