diff --git a/src/ch/zhaw/ads/SortServer.java b/src/ch/zhaw/ads/SortServer.java index f60e92b..48908f0 100644 --- a/src/ch/zhaw/ads/SortServer.java +++ b/src/ch/zhaw/ads/SortServer.java @@ -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; }