Advertisement
OreganoHauch

Matlab_ExerciseSheet3

Nov 6th, 2023
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.89 KB | None | 0 0
  1. function x = SHEET3TASK2(x)
  2. n = numel(x);
  3. if n == 1
  4. return
  5. end
  6. min_ind = finde_min(x,n);
  7. if min_ind > 1
  8. x = tausche(x,1,min_ind);
  9. end
  10. x(2:n) = SHEET3TASK2(x(2:n));
  11. end
  12.  
  13. function ind = finde_min(x,n)
  14. ind = 1;
  15. ind_value = x(1);
  16. for k=2:n
  17. if x(k) < ind_value
  18. ind = k;
  19. ind_value = x(k);
  20. end
  21. end
  22. end
  23.  
  24. function x = tausche(x,ind1,ind2)
  25. merke_x_ind1 = x(ind1);
  26. x(ind1) = x(ind2);
  27. x(ind2) = merke_x_ind1;
  28. end
  29.  
  30. --------------------
  31.  
  32. function [x,indices] = SHEET3TASK2b(x)
  33. n = numel(x);
  34. indices = 1:n;
  35. if n==1
  36. return
  37. end
  38. for k=1:n-1
  39. min_ind = finde_min(x(k:n),n-k+1);
  40. %disp(["k=",k, ": ", "min_ind=",min_ind])
  41. if min_ind > 1
  42. x = tausche(x,k,min_ind+k-1);
  43. indices = tausche(indices,k,min_ind+k-1);
  44. end
  45. end
  46. end
  47.  
  48. function ind = finde_min(x,n)
  49. ind = 1;
  50. ind_value = x(1);
  51. for k=2:n
  52. if x(k) < ind_value
  53. ind = k;
  54. ind_value = x(k);
  55. end
  56. end
  57. end
  58.  
  59. function x = tausche(x,ind1,ind2)
  60. merke_x_ind1 = x(ind1);
  61. x(ind1) = x(ind2);
  62. x(ind2) = merke_x_ind1;
  63. end
  64.  
  65. -----------
  66.  
  67. function x_sorted = SHEET3TASK3(x)
  68. n = numel(x);
  69. if n<=1
  70. return
  71. end
  72. mitte = floor(n/2);
  73. links = x(1:mitte);
  74. links = SHEET3TASK3(links);
  75. rechts = x(mitte+1:n);
  76. rechts = SHEET3TASK3(rechts);
  77. x_sorted = verschmelze(links,rechts);
  78. end
  79.  
  80. function x = verschmelze(links,rechts)
  81. n_links = numel(links);
  82. n_rechts = numel(rechts);
  83. x = zeros(1,n_links+n_rechts);
  84. k = 1;
  85. while n_links ~= 0 && n_rechts ~= 0
  86. if rechts(1) < links(1)
  87. x(k) = rechts(1);
  88. rechts = rechts(2:end);
  89. n_rechts = n_rechts-1;
  90. else
  91. x(k) = links(1);
  92. links = links(2:end);
  93. n_links = n_links-1;
  94. end
  95. k = k+1;
  96. end
  97. if n_links == 0 && n_rechts == 1
  98. x(end-n_rechts+1) = rechts(1:n_rechts);
  99. end
  100. if n_rechts == 0 && n_links == 1
  101. x(end-n_links+1) = links(1:n_links);
  102. end
  103. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement