Advertisement
Mazamin

quickSort

Nov 18th, 2019
141
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.21 KB | None | 0 0
  1. /*
  2.  * File:   main.c
  3.  * Author: Gerardo Cicalese
  4.  *
  5.  * Created on 18 novembre 2019, 14.22
  6.  */
  7.  
  8. #include <stdio.h>
  9. #include <stdlib.h>
  10. #include <time.h>
  11.  
  12. typedef char Info;
  13.  
  14. void quickSort(Info *, int);
  15. int partition(Info *, int);
  16. void swap(Info *, Info *);
  17. int compare(Info, Info);
  18.  
  19. int main(void)
  20. {
  21.     srand(time(NULL));
  22.     Info array[10];
  23.    
  24.     for(int i=0; i<10; ++i)
  25.         array[i] = 'a' + rand()%('z' - 'a' + 1);
  26.    
  27.     quickSort(array, 10);
  28.    
  29.     for(int i=0; i<10; ++i)
  30.         printf("%c\t", array[i]);
  31.    
  32.     return 0;
  33. }
  34.  
  35. void quickSort(Info * array, int len)
  36. {
  37.     if(len <= 1)
  38.         return;
  39.    
  40.     int pivot = partition(array, len);
  41.     quickSort(array, pivot);
  42.     quickSort(array+pivot+1, len-pivot-1);
  43. }
  44.  
  45. int partition(Info * array, int len)
  46. {
  47.     int i = 1, j = 1;
  48.    
  49.     for(; i < len; ++i)
  50.         if(-1 == compare(array[i], array[0]))
  51.             swap(array+i, array+j++);
  52.  
  53.     swap(array, array+j-1);
  54.     return j-1;
  55. }
  56.  
  57. void swap(Info * a, Info * b)
  58. {
  59.     Info temp = *a;
  60.     *a = *b;
  61.     *b = temp;
  62. }
  63.  
  64. int compare(Info a, Info b)
  65. {
  66.     if(a == b)
  67.         return 0;
  68.    
  69.     if(a > b)
  70.         return 1;
  71.    
  72.     return -1;
  73. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement