Advertisement
Tobiahao

Kolokwium2_Quicksort

Jun 7th, 2017
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.38 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <time.h>
  4. #define ILOSC_NUMBEROW 10
  5.  
  6. typedef int int_array_type[ILOSC_NUMBEROW];
  7.  
  8. void fill_array(int_array_type array)
  9. {
  10.     int i;
  11.     for(i = 0; i < sizeof(int_array_type)/sizeof(array[0]); i++)
  12.         array[i] = rand() % 100;
  13. }
  14.  
  15. void print_array(int_array_type array)
  16. {
  17.     int i;
  18.     for(i = 0; i < sizeof(int_array_type)/sizeof(array[0]); i++)
  19.         printf("%d ", array[i]);
  20.     printf("\n");
  21. }
  22.  
  23. void swap(int *first, int *second)
  24. {
  25.     int tmp = *first;
  26.     *first = *second;
  27.     *second = tmp;
  28. }
  29.  
  30. int partition(int_array_type array, int low, int high)
  31. {
  32.     int pivot = array[low];
  33.     int i = low - 1;
  34.     int j = high + 1;
  35.  
  36.     while(i < j){
  37.         while(array[--j] > pivot)
  38.             ;
  39.         while(array[++i] < pivot)
  40.             ;
  41.         if(i < j)
  42.             swap(&array[i], &array[j]);
  43.     }
  44.     return j;
  45. }
  46.  
  47. void quicksort(int_array_type array, int low, int high)
  48. {
  49.     if(low < high){
  50.         int partition_index = partition(array, low, high);
  51.         quicksort(array, low, partition_index);
  52.         quicksort(array, partition_index+1, high);
  53.     }
  54. }
  55.  
  56. int main(void)
  57. {
  58.     srand(time(NULL));
  59.     int_array_type array;
  60.  
  61.     fill_array(array);
  62.     print_array(array);
  63.  
  64.     quicksort(array, 0, sizeof(int_array_type)/sizeof(array[0])-1);
  65.  
  66.     print_array(array);
  67.  
  68.     return 0;
  69. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement