Advertisement
Guest User

Zeit vergleich

a guest
Sep 25th, 2018
164
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.19 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <time.h>
  4.  
  5. #define N 20000
  6.  
  7. // Iterativ
  8. void insertionSort(int arr[], int n)
  9. {
  10.    int i, j, key;
  11.    
  12.    for (i = 1; i < n; i++)
  13.    {
  14.        key = arr[i];
  15.        j = i-1;
  16.        
  17.        while (j >= 0 && arr[j] > key)
  18.        {
  19.            arr[j+1] = arr[j];
  20.            j = j-1;
  21.        }
  22.        arr[j+1] = key;
  23.    }
  24. }
  25.  
  26. // Rekursiv
  27. void insertionSortRecursive(int arr[], int n)
  28. {
  29.     if (n <= 1)
  30.         return;
  31.  
  32.     insertionSortRecursive(arr, n-1);
  33.  
  34.     int last = arr[n-1];
  35.     int j = n-2;
  36.  
  37.     while (j >= 0 && arr[j] > last)
  38.     {
  39.         arr[j+1] = arr[j];
  40.         j--;
  41.     }
  42.     arr[j+1] = last;
  43. }
  44.  
  45. int main(){
  46.     int A[N], B[N];
  47.     int i;
  48.     for(i = 0; i < N; i++){
  49.         B[i] = A[i] = 1 + rand()%1000;
  50.     }
  51.    
  52.     clock_t start, ende;
  53.     double a_zeit;
  54.    
  55.     printf("InsertionSort Iterativ:\n");
  56.     start = clock();
  57.     insertionSort(A, N);
  58.     ende = clock();
  59.     a_zeit = (double)(ende-start)/CLOCKS_PER_SEC;  
  60.     printf("Zeit: %fs\n", a_zeit);
  61.    
  62.     printf("InsertionSort Rekursiv:\n");
  63.     start = clock();
  64.     insertionSortRecursive(B, N);
  65.     ende = clock();
  66.     a_zeit = (double)(ende-start)/CLOCKS_PER_SEC;
  67.     printf("Zeit: %fs\n", a_zeit);
  68. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement