You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
86 lines
2.8 KiB
86 lines
2.8 KiB
import java.util.Arrays;
|
|
import java.util.Random;
|
|
import java.util.stream.IntStream;
|
|
|
|
public class Suchalgorythmen {
|
|
public static void main(String[] args) {
|
|
|
|
int[] list1 = IntStream.generate(() -> new Random().nextInt(100)).limit(100).toArray();
|
|
int[] list2 = Arrays.copyOf(list1, list1.length);
|
|
|
|
// aufruf lineare Suche
|
|
System.out.print("COUNTINGSORT: ");
|
|
long timeStart = System.nanoTime();
|
|
COUNTINGSORT(list1);
|
|
long timeEnd = System.nanoTime();
|
|
// System.out.println(Arrays.toString(list1));
|
|
System.out.print(" Verlaufszeit: " + (timeEnd - timeStart) + " Nanosek.");
|
|
System.out.println("");
|
|
|
|
// aufruf binäre Suche
|
|
System.out.print("RADIXSORT: ");
|
|
timeStart = System.nanoTime();
|
|
RADIXSORT(list2, 0, list2.length - 1);
|
|
timeEnd = System.nanoTime();
|
|
// System.out.println(Arrays.toString(list2));
|
|
System.out.print(" Verlaufszeit: " + (timeEnd - timeStart) + " Nanosek.");
|
|
System.out.println("");
|
|
}
|
|
|
|
public static void COUNTINGSORT(int[] elements) {
|
|
int maxValue = maxValue(elements);
|
|
int[] counts = new int[maxValue + 1];
|
|
// Phase 1: Count
|
|
for (int element : elements) {
|
|
counts[element]++;
|
|
}
|
|
// Phase 2: Aggregate
|
|
for (int i = 1; i <= maxValue; i++) {
|
|
counts[i] += counts[i - 1];
|
|
}
|
|
// Phase 3: Write to target array
|
|
int[] target = new int[elements.length];
|
|
for (int i = elements.length - 1; i >= 0; i--) {
|
|
int element = elements[i];
|
|
target[--counts[element]] = element;
|
|
}
|
|
// Copy target back to input array
|
|
//System.arraycopy(target, 0, elements, 0, elements.length);
|
|
System.out.println(Arrays.toString(target));
|
|
}
|
|
|
|
public static int maxValue(int[] chars) {
|
|
int max = chars[0];
|
|
for (int ktr = 0; ktr < chars.length; ktr++) {
|
|
if (chars[ktr] > max) {
|
|
max = chars[ktr];
|
|
}
|
|
}
|
|
return max;
|
|
}
|
|
|
|
// vorraussetzung: eingabe Array muss sortiert sein
|
|
public static void RADIXSORT(int arr[], int low, int high) {
|
|
|
|
// Find the maximum number to
|
|
// know number of digits
|
|
int m = maxValue(arr);
|
|
|
|
// Do counting sort for every digit.
|
|
// Note that instead of passing digit
|
|
// number, exp is passed. exp is 10^i
|
|
// where i is current digit number
|
|
for (int exp = 1; m / exp > 0; exp *= 10)
|
|
COUNTINGSORT(arr);
|
|
}
|
|
|
|
static void random(int arr[], int low, int high) {
|
|
|
|
Random rand = new Random();
|
|
int pivot = rand.nextInt(high - low) + low;
|
|
|
|
int temp1 = arr[pivot];
|
|
arr[pivot] = arr[high];
|
|
arr[high] = temp1;
|
|
}
|
|
}
|