sovled Tasks

This commit is contained in:
schrom01 2022-11-30 08:16:26 +01:00
parent 28edb90e83
commit 9d99b948c1
1 changed files with 47 additions and 1 deletions

View File

@ -1,7 +1,9 @@
package ch.zhaw.ads;
import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.Map;
import java.util.Random;
import java.util.function.Consumer;
import java.util.function.Supplier;
@ -17,14 +19,45 @@ public class SortServer implements CommandExecutor {
public void bubbleSort(int[] a) {
// TODO Implement Aufgabe 1
for (int k = a.length-1; k > 0; k--) {
boolean noSwap = true;
for (int i = 0; i < k; i++) {
if ( a[i] > a[i + 1]) {
swap (a, i, i + 1);
noSwap = false;
}
}
if (noSwap){
break;
}
}
}
public void insertionSort(int[] a) {
// TODO Implement Aufgabe 3
for (int k = 1; k < a.length; k++) {
int x = a[k];
int i = k;
for (; ((i > 0) && (a[i-1] > x)); i--) {
a[i] = a[i-1];
}
a[i] = x;
}
}
public void selectionSort(int[] a) {
// TODO Implement Aufgabe 3
for (int k = 0; k < a.length; k++) {
int min = k;
for (int i = k + 1; i < a.length; i++) {
if (a[i] < a[min]){
min = i;
}
}
if (min != k) {
swap(a, min, k);
}
}
}
public void streamSort(int[] a) {
@ -35,12 +68,18 @@ public class SortServer implements CommandExecutor {
public boolean isSorted(int[] a) {
// TODO Implement Aufgabe 1
for(int i = 0; i < a.length - 1; i++) {
if(a[i] >= a[i + 1]) {
return false;
}
}
return true;
}
public int[] randomData() {
int[] a = new int[dataElems];
// TODO Implement Aufgabe 1
a = new Random().ints(dataElems).toArray();
return a;
}
@ -71,8 +110,15 @@ public class SortServer implements CommandExecutor {
long endTime = startTime;
// TODO Implement Aufgabe 1 und 2 (Tipp: siehe Consumer für Aufruf von Sortiermethode)
int count = 0;
while (endTime < startTime + 1000) {
b = Arrays.copyOf(a, dataElems);
sorter.accept(b);
count++;
endTime = System.currentTimeMillis();
}
elapsed = (double)(endTime - startTime);
elapsed = (double)(endTime - startTime) / count;
if (!isSorted(b)) throw new Exception ("ERROR not sorted");
return elapsed;
}