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.

85 lines
2.8 KiB

1 year ago
  1. import java.util.Arrays;
  2. import java.util.Random;
  3. import java.util.stream.IntStream;
  4. public class Suchalgorythmen {
  5. public static void main(String[] args) {
  6. int[] list1 = IntStream.generate(() -> new Random().nextInt(100)).limit(100).toArray();
  7. int[] list2 = Arrays.copyOf(list1, list1.length);// Terrys Kommentar
  8. // aufruf lineare Suche
  9. System.out.print("COUNTINGSORT: ");
  10. long timeStart = System.nanoTime();
  11. COUNTINGSORT(list1);
  12. long timeEnd = System.nanoTime();
  13. // System.out.println(Arrays.toString(list1));
  14. System.out.print(" Verlaufszeit: " + (timeEnd - timeStart) + " Nanosek.");
  15. System.out.println("");
  16. // aufruf binäre Suche
  17. System.out.print("RADIXSORT: ");
  18. timeStart = System.nanoTime();
  19. RADIXSORT(list2, 0, list2.length - 1);
  20. timeEnd = System.nanoTime();
  21. // System.out.println(Arrays.toString(list2));
  22. System.out.print(" Verlaufszeit: " + (timeEnd - timeStart) + " Nanosek.");
  23. System.out.println("");
  24. }
  25. public static void COUNTINGSORT(int[] elements) {
  26. int maxValue = maxValue(elements);
  27. int[] counts = new int[maxValue + 1];
  28. // Phase 1: Count
  29. for (int element : elements) {
  30. counts[element]++;
  31. }
  32. // Phase 2: Aggregate
  33. for (int i = 1; i <= maxValue; i++) {
  34. counts[i] += counts[i - 1];
  35. }
  36. // Phase 3: Write to target array
  37. int[] target = new int[elements.length];
  38. for (int i = elements.length - 1; i >= 0; i--) {
  39. int element = elements[i];
  40. target[--counts[element]] = element;
  41. }
  42. // Copy target back to input array
  43. //System.arraycopy(target, 0, elements, 0, elements.length);
  44. System.out.println(Arrays.toString(target));
  45. }
  46. public static int maxValue(int[] chars) {
  47. int max = chars[0];
  48. for (int ktr = 0; ktr < chars.length; ktr++) {
  49. if (chars[ktr] > max) {
  50. max = chars[ktr];
  51. }
  52. }
  53. return max;
  54. }
  55. // vorraussetzung: eingabe Array muss sortiert sein
  56. public static void RADIXSORT(int arr[], int low, int high) {
  57. // Find the maximum number to
  58. // know number of digits
  59. int m = maxValue(arr);
  60. // Do counting sort for every digit.
  61. // Note that instead of passing digit
  62. // number, exp is passed. exp is 10^i
  63. // where i is current digit number
  64. for (int exp = 1; m / exp > 0; exp *= 10)
  65. COUNTINGSORT(arr);
  66. }
  67. static void random(int arr[], int low, int high) {
  68. Random rand = new Random();
  69. int pivot = rand.nextInt(high - low) + low;
  70. int temp1 = arr[pivot];
  71. arr[pivot] = arr[high];
  72. arr[high] = temp1;
  73. }
  74. }