Advertisement
madegoff

MergeSort (rekursiv)

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