-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSortingTest.java
More file actions
102 lines (83 loc) · 2.93 KB
/
SortingTest.java
File metadata and controls
102 lines (83 loc) · 2.93 KB
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
/* ************************************************
* Classe per testare gli algoritmi di ordinamento.
*
* Esempio di esecuzione::
*
* java SortingTest file selectionsort
*
* dove "file" è il nome di un file contenente interi
* e selectionsort è uno degli algoritmi di ordinamento
* fornini dalla classe Sorting.
*
* Attenzione: l'algoritmo quicksort potrebbe causare
* stack overflow. In tal caso, modificare la dimensione
* dello stack della JVM con il seguente comando:
*
* java -Xss20m SortingTest file quicksort
*
* *************************************************/
import java.util.Arrays;
import java.util.ArrayList;
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import java.lang.reflect.Method;
import algorithm.sorting.Sorting;
public class SortingTest {
private static int[] readarray(String filename) throws FileNotFoundException {
ArrayList<Integer> L = new ArrayList<Integer>();
Scanner input = new Scanner(new File(filename));
while(input.hasNext())
L.add(input.nextInt());
return L.stream().mapToInt(Integer::intValue).toArray();
}
private static int[] savesorted(int A[]) {
int[] B = A.clone();
Arrays.sort(B);
return B;
}
private static boolean issorted(int A[], int B[]) {
for(int i = 0; i < A.length-1; i++)
if(A[i] != B[i])
return false;
return true;
}
public static void main(String args[]) {
Sorting S = new Sorting();
Method M = null;
int A[] = null;
int B[] = null;
if(args.length != 2) {
System.err.println("Usage: SortingTest <filename> <sorting algorithm>\n");
System.err.println("Sorting algorithms:");
for (Method m : S.getClass().getMethods()) {
if (m.getDeclaringClass() == S.getClass() && m.getParameterTypes()[0].equals(int[].class))
System.err.println("- " + m.getName());
}
System.exit(0);
}
try {
M = S.getClass().getDeclaredMethod(args[1],int[].class);
} catch(Exception e) {
System.out.println(e.toString());
System.exit(1);
}
try {
A = readarray(args[0]);
B = savesorted(A);
} catch(Exception e) {
System.out.println(e.toString());
System.exit(1);
}
try {
long start = System.currentTimeMillis();
M.invoke(S,A);
long end = System.currentTimeMillis();
//System.out.println(Arrays.toString(A));
System.out.println("Algorithm: " + args[1] + " \tTime: " + (end-start)/1000.0 + "s " + (issorted(A,B) ? "[SORTED]" : "[UNSORTED]"));
} catch(Exception e) {
e.printStackTrace();
System.exit(1);
}
}
}