Skip to content

Commit 91ed1ab

Browse files
committed
Arrays.sort()的使用
1 parent 64ea2c5 commit 91ed1ab

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed

docs/book/21-Arrays.md

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2418,8 +2418,64 @@ After sorting: [[i = 21, j = 6], [i = 70, j = 7], [i = 41, j = 20] ,
24182418
*/
24192419
```
24202420

2421+
<!-- Using Arrays.sort() -->
2422+
## Arrays.sort()的使用
24212423

2424+
使用内置的排序方法,您可以对实现了 **Comparable** 接口或具有 **Comparator** 的任何对象数组 或 任何原生数组进行排序。这里我们生成一个随机字符串对象数组并对其排序:
24222425

2426+
```JAVA
2427+
// arrays/StringSorting.java
2428+
// Sorting an array of Strings
2429+
2430+
import onjava.*;
2431+
2432+
import java.util.Arrays;
2433+
import java.util.Collections;
2434+
2435+
import static onjava.ArrayShow.*;
2436+
2437+
public class StringSorting {
2438+
public static void main(String[] args) {
2439+
String[] sa = new Rand.String().array(20);
2440+
show("Before sort", sa);
2441+
Arrays.sort(sa);
2442+
show("After sort", sa);
2443+
Arrays.sort(sa, Collections.reverseOrder());
2444+
show("Reverse sort", sa);
2445+
Arrays.sort(sa, String.CASE_INSENSITIVE_ORDER);
2446+
show("Case-insensitive sort", sa);
2447+
}
2448+
}
2449+
/* Output:
2450+
Before sort: [btpenpc, cuxszgv, gmeinne, eloztdv, ewcippc,
2451+
ygpoalk, ljlbynx, taprwxz, bhmupju, cjwzmmr,
2452+
anmkkyh, fcjpthl, skddcat, jbvlgwc, mvducuj,
2453+
ydpulcq, zehpfmm, zrxmclh, qgekgly, hyoubzl]
2454+
2455+
After sort: [anmkkyh, bhmupju, btpenpc, cjwzmmr, cuxszgv,
2456+
eloztdv, ewcippc, fcjpthl, gmeinne, hyoubzl,
2457+
jbvlgwc, ljlbynx, mvducuj, qgekgly, skddcat,
2458+
taprwxz, ydpulcq, ygpoalk, zehpfmm, zrxmclh]
2459+
2460+
Reverse sort: [zrxmclh, zehpfmm, ygpoalk, ydpulcq,taprwxz,
2461+
skddcat, qgekgly, mvducuj, ljlbynx, jbvlgwc,
2462+
hyoubzl, gmeinne, fcjpthl, ewcippc, eloztdv,
2463+
cuxszgv, cjwzmmr, btpenpc, bhmupju, anmkkyh]
2464+
2465+
Case-insensitive sort: [anmkkyh, bhmupju, btpenpc, cjwzmmr,
2466+
cuxszgv, eloztdv, ewcippc, fcjpthl, gmeinne,
2467+
hyoubzl, jbvlgwc, ljlbynx, mvducuj, qgekgly,
2468+
skddcat, taprwxz, ydpulcq, ygpoalk, zehpfmm, zrxmclh]
2469+
*/
2470+
```
2471+
2472+
注意字符串排序算法中的输出。它是字典式的,所以它把所有以大写字母开头的单词放在前面,然后是所有以小写字母开头的单词。(电话簿通常是这样分类的。)无论大小写,要将单词组合在一起,请使用 **String.CASE_INSENSITIVE_ORDER** ,如对sort()的最后一次调用所示。
2473+
2474+
Java标准库中使用的排序算法被设计为最适合您正在排序的类型----原生类型的快速排序和对象的归并排序。
2475+
2476+
2477+
<!-- Sorting in Parallel -->
2478+
## 并行排序
24232479

24242480
<!-- Searching with Arrays.binarySearch() -->
24252481
## binarySearch二分查找

0 commit comments

Comments
 (0)