Advertisement
madegoff

MergeSort (iterativ)

Jan 11th, 2023 (edited)
174
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.66 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <assert.h>
  4. #include "introprog_input_merge_sort.h"
  5.  
  6. void merge(int* array, int first, int middle, int last)
  7. {
  8.     int length = last - first + 1;
  9.     int* b = (int*) calloc(length, sizeof(int));
  10.  
  11.     int k = first;
  12.     int m = middle + 1;
  13.     int i = 0;
  14.  
  15.     while (k <= middle && m <= last)
  16.     {
  17.         if (array[k] <= array[m]){
  18.             b[i] = array[k];
  19.             k += 1;
  20.         }else {
  21.             b[i] = array[m];
  22.             m += 1;
  23.         }
  24.         i += 1;
  25.     }
  26.  
  27.     while (k <= middle)
  28.     {
  29.         b[i] = array[k];
  30.         k += 1;
  31.         i += 1;
  32.     }
  33.  
  34.     while (m <= last)
  35.     {
  36.         b[i] = array[m];
  37.         m += 1;
  38.         i += 1;
  39.     }
  40.  
  41.     int j = 0;
  42.  
  43.     while (j < i)
  44.     {
  45.         array[first + j] = b[j];
  46.         j += 1;
  47.     }
  48.  
  49.     free(b);
  50. }
  51.  
  52. void merge_sort(int* array, int last)
  53. {
  54.     int left, right, middle;
  55.  
  56.     int step = 1;
  57.     while (step <= last){
  58.     left = 0;
  59.     while (left <= last-step){
  60.         int m = left + step - 1;
  61.         if (last <= m)
  62.         {
  63.             middle = last;
  64.         }
  65.         else middle = m;
  66.  
  67.         int r = left + 2*step - 1;
  68.         if (last <= r)
  69.         {
  70.             right = last;
  71.         }
  72.         else right = r;
  73.  
  74.         merge(array, left, middle, right);
  75.  
  76.         left = left + 2*step;
  77.     }
  78.     step = step*2;
  79.     }
  80. }
  81.  
  82. int main (int argc, char *argv[])
  83. {
  84.     if (argc!=3){
  85.         printf ("usage: %s <maximale anzahl>  <dateipfad>\n", argv[0]);
  86.         exit(2);
  87.     }
  88.  
  89.     char *filename = argv[2];
  90.     int* array = (int*)malloc(atoi(argv[1]) * sizeof(int));    
  91.     int len = read_array_from_file(array, atoi(argv[1]), filename);
  92.  
  93.  
  94.     printf("Eingabe:\n");
  95.     print_array(array, len);
  96.  
  97.     merge_sort(array, len-1);
  98.  
  99.     printf("Sortiert:\n");
  100.     print_array(array, len);
  101.  
  102.     free(array);
  103.  
  104.     return 0;
  105. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement