Guest User

Untitled

a guest
Jul 17th, 2018
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.19 KB | None | 0 0
  1. public class mergeSort {
  2.  
  3. public static void main(String args[]) {
  4.  
  5. int zahlen[] = {9 ,4 ,5, 8};
  6. int [] ausgabe = new int[zahlen.length];
  7.  
  8. for (int i = 0; i < zahlen.length; i++) {
  9. System.out.print(zahlen[i] + " ");
  10. }
  11. System.out.println();
  12. ausgabe = mergeSort_sort(zahlen, 0, zahlen.length - 1);
  13. System.out.print("sorted:\n");
  14. for (int i = 0; i < zahlen.length; i++) {
  15. System.out.print(ausgabe[i] + " ");
  16. }
  17. System.out.println();
  18. }
  19.  
  20. public static int[] mergeSort_sort(int zahlen[], int min, int max) {
  21.  
  22.  
  23. int low = min;
  24. int high = max;
  25. int[] tmp = new int[high+1]; //high als Größe auf Grund der Rekursion
  26. //Kopieren des Arrays in tmp
  27. for (int i = 0; i < tmp.length; i++) {
  28. tmp[i] = zahlen[i];
  29. }
  30.  
  31. if (low >= high) { // Abbruchbedingung der Rekursion
  32. return zahlen;
  33. } else {
  34. int middle = (low + high) / 2;
  35.  
  36. mergeSort_sort(tmp, low, middle); //Übergabe der linken Liste an mergeSort_sort
  37. mergeSort_sort(tmp, middle + 1, high); //Übergabe der rechten Liste an mergeSort_sort
  38.  
  39. int end_low = middle; // Ende linke Liste
  40. int start_high = middle + 1; // Anfang rechte Liste
  41. int a = 0;
  42.  
  43. //Vergleichen und einfügen
  44. while ((low <= end_low) && (start_high <= high)) {
  45. if (tmp[low] < tmp[start_high]) {
  46. zahlen[a] = tmp[low];
  47. a++;
  48. low++;
  49. } else {
  50. zahlen[a] = tmp[start_high];
  51. a++;
  52. start_high++;
  53. }
  54. }
  55. // Rest linker Liste einfügen
  56. while (low < end_low) {
  57. zahlen[a] = tmp[low];
  58. a++;
  59. low++;
  60. }
  61. // Rest rechter Liste einfügen
  62. while (start_high < high-1) {
  63. zahlen[a] = tmp[high];
  64. a++;
  65. high++;
  66. }
  67. return zahlen;
  68. }
  69. }
  70. }
Add Comment
Please, Sign In to add comment