-
Notifications
You must be signed in to change notification settings - Fork 151
/
Copy pathEx_2_1_07.java
43 lines (37 loc) · 1.26 KB
/
Ex_2_1_07.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package Ch_2_1;
import Ch_1_4._Stopwatch;
import edu.princeton.cs.algs4.StdOut;
import tools.ArrayGenerator;
/**
* Created by HuGuodong on 2019-09-01.
*/
public class Ex_2_1_07 {
public static double time(String alg, int size, int N) {
double totalTime = 0.0;
for (int i = 0; i < N; i++) {
Integer[] a = ArrayGenerator.descIntArray(0, size);
_Stopwatch time = new _Stopwatch();
if (alg.equals("select")) {
_SelectionSort.sort(a);
} else if (alg.equals("insertion")) {
_InsertionSort.sort(a);
}
totalTime += time.elapsedTime();
}
return totalTime;
}
public static void main(String[] args) {
int arraySize = 1000;
int N = 10000;
double timeSelect = time("select", arraySize, N);
double timeInsertion = time("insertion", arraySize, N);
StdOut.printf("selection sort uses: %.3fs\n", timeSelect);
StdOut.printf("insertion sort uses: %.3fs\n", timeInsertion);
StdOut.printf(
"arraySize is %2d, run %2d times, insertion sort use %.3f times than selection sort\n",
arraySize, N, timeInsertion / timeSelect);
// selection sort uses: 4.876s
// insertion sort uses: 15.736s
// arraySize is 1000, run 10000 times, insertion sort use 3.227 times than selection sort
}
}