Elementary Sorts
1 排序介绍(rules of the game)
1.1 示例
- 给0-1之间的小数升序排序
package Chapter02;
import edu.princeton.cs.algs4.StdOut;
import edu.princeton.cs.algs4.StdRandom;
import edu.princeton.cs.algs4.Insertion;
//Sort random real numbers in ascending order
public class Experiment {
public static void main(String[] args) {
//在命令行输入要生成几个随机数
int N = Integer.parseInt(args[0]); //将字符串参数解析为带符号的十进制整数
Double[] a = new Double[N]; //生成含有N个元素的数组a
for (int i = 0; i < N; i++) {
a[i] = StdRandom.uniform();//Returns a random real number uniformly in [0, 1)
}
Insertion.sort(a); //Rearranges the array in ascending order, using the natural order
for (int i = 0; i < N; i++) {
StdOut.println(a[i]);
}
}
}
/*
正常run(不需在terminal):
public static void main(String[] args) {
Double[] a = new Double[10];
for (int i = 0; i < 10; i++) {
a[i] = StdRandom.uniform();//Returns a random real number uniformly in [0, 1)
}
Insertion.sort(a); //升序
for (int i = 0; i < 10; i++) {
StdOut.println(a[i]);
}
}
*/
- 文件内容按字母顺序排序
package Chapter02;
import edu.princeton.cs.algs4.In;
import edu.princeton.cs.algs4.Insertion;
import edu.princeton.cs.algs4.StdOut;
//文件内容按字母顺序排序
public class StringSorter {
public static void main(String[] args) {
String[] a = In.readStrings(args[0]);
Insertion.sort(a);
for (int i = 0; i < a.length; i++) {
StdOut.println(a[i]);
}
}
}
/*
原文件:
bed bug dad yes zoo
now for tip ilk dim
tag jot sob nob sky
hut men egg few jay
owl joy rap gig wee
was wad fee tap tar
dug jam all bad yet
运行结果:
all
bad
bed
bug
dad
dim
dug
egg
fee
few
for
gig
hut
ilk
jam
jay
jot
joy
men
nob
now
owl
rap
sky
sob
tag
tap
tar
tip
wad
was
wee
yes
yet
zoo
*/
- 文件名按字母排序
package Chapter02;
import edu.princeton.cs.algs4.Insertion;
import edu.princeton.cs.algs4.StdOut;
import java.io.File<