Advertisement
Wojtekd

Sortowanie algorytmem quicksort [Tablice]

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