Advertisement
Wojtekd

Quicksort

Apr 15th, 2015
230
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.21 KB | None | 0 0
  1. #include <stdio.h>
  2.  
  3. void swapValues(int *ElementA,int *ElementB);
  4. void quicksort(int t[], int p, int q);
  5. int partition(int t[], int p, int q);
  6.  
  7. #define ARRAY_SIZE 17
  8.  
  9. void displayArray(int t[],int size)
  10. {
  11.         printf("\n");
  12.         for(int i = 0; i < size; i ++)
  13.         {
  14.                 printf("%d  ",t[i]);
  15.         }
  16. }
  17. int main ( void )
  18. {
  19.         int t[] = { 9, 2, 4, 7, 3, 1, -5, 6, 5, 8, 3, -9, -2, -6, -7, -3, 0 };
  20.         displayArray(t, 17);
  21.  
  22.         partition(t,0,16);
  23.         //quicksort(t,0,16);
  24.  
  25.         displayArray(t, 17);
  26.  
  27.         getchar();
  28.         return 0;
  29. }
  30. void quicksort(int t[], int p, int q)
  31. {
  32.     if(p < q)
  33.     {
  34.         int r = partition(t,p,q);
  35.         quicksort(t,p,r-1);
  36.         quicksort(t,r+1,q);
  37.     }
  38. }
  39. int partition(int t[], int p, int q)
  40. {
  41.     int x = t[q];
  42.     printf("pivot: %d",x);
  43.    
  44.     int i = p, j;
  45.    
  46.     for(j = p + 1; j < q; j++)
  47.     {
  48.             if(t[j] < x)
  49.             {
  50.                     swapValues(&t[j],&t[i]);
  51.                     i++;
  52.             }
  53.     }
  54.     swapValues(&t[i],&t[q]);
  55.     return i;
  56. }
  57. void swapValues(int *ElementA,int *ElementB)
  58. {
  59.         int temp = *ElementA;
  60.         *ElementA = *ElementB;
  61.         *ElementB = temp;
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement