solved s12 ex2
This commit is contained in:
parent
1d862d57bc
commit
d9414c81ed
@ -1,24 +1,39 @@
|
||||
package ch.zhaw.ads;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Random;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
public class QuickerSortServer implements CommandExecutor {
|
||||
int QUICKSORT_THRESHOLD = 70;
|
||||
|
||||
@Override
|
||||
public String execute(String command) {
|
||||
StringBuffer result = new StringBuffer();
|
||||
|
||||
int[] testdata = new int[1000];
|
||||
Random random = new Random();
|
||||
for (int i=0; i < testdata.length; i++) {
|
||||
testdata[i] = random.nextInt(1000000);
|
||||
}
|
||||
quickSort(testdata);
|
||||
return "Is sorted: " + checkSorted(testdata);
|
||||
|
||||
double arraysSortRuntime = timeit(Arrays::sort, testdata);
|
||||
result.append("Is sorted: " + checkSorted(testdata) + "\n");
|
||||
result.append("quickSort runtime: " + arraysSortRuntime + "ms\n");
|
||||
result.append("quickSort runtime:\n");
|
||||
// for (int i = 0; i < 1000; i++)
|
||||
for (int i = 40; i < 100; i++) {
|
||||
QUICKSORT_THRESHOLD = i;
|
||||
double quickSortRuntime = timeit(this::quickSort, testdata);
|
||||
result.append(QUICKSORT_THRESHOLD + "," + quickSortRuntime + "\n");
|
||||
}
|
||||
return result.toString();
|
||||
}
|
||||
|
||||
private void quickSort(int[] a, int left, int right) {
|
||||
if (left < right) {
|
||||
int mid = partition (a, left, right);
|
||||
if (mid <= 50) {
|
||||
if (mid <= QUICKSORT_THRESHOLD) {
|
||||
insertSort(a);
|
||||
} else {
|
||||
quickSort(a, left, mid-1);
|
||||
@ -68,4 +83,17 @@ public class QuickerSortServer implements CommandExecutor {
|
||||
a[i] = x;
|
||||
}
|
||||
}
|
||||
|
||||
private double timeit(Consumer<int[]>func, int[] a) {
|
||||
long end, start = System.currentTimeMillis();
|
||||
int count = 0;
|
||||
int[] testarray = new int[a.length];
|
||||
do {
|
||||
System.arraycopy(a, 0, testarray, 0, a.length);
|
||||
func.accept(testarray);
|
||||
count++;
|
||||
end = System.currentTimeMillis();
|
||||
} while (end - start < 1000);
|
||||
return (double)(end-start)/count;
|
||||
}
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user