ioana_martin98

quicksort

May 8th, 2019
227
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.83 KB | None | 0 0
  1. #include<iostream.h>
  2. int v[100],n;
  3.  
  4. void citire()
  5. {
  6.     int i;
  7.     cin>>n;
  8.     for(i=1;i<=n;i++)
  9.         cin>>v[i];
  10. }
  11. void afisare()
  12. {
  13.     int i;
  14.     for(i=1;i<=n;i++)
  15.         cout<<v[i]<<' ';
  16.     cout<<endl;
  17. }
  18. int divide(int st, int dr)
  19. {
  20.     /*plaseaza elementul v[st] pe pozitia sa corecta in vectorul ordonat
  21.     in stanga sa sunt plasate numai elemente mai mici, iar in dreapta numai elemente mai mari
  22.     si intoarce pozitia pe care a fost plasat a[st]*/
  23.     int x;
  24.     x=v[st];
  25.     while(st<dr)
  26.     {
  27.         while(st<dr && v[dr]>=x)
  28.             dr--;
  29.         v[st]=v[dr];
  30.         while(st<dr && v[st]<=x)
  31.             st++;
  32.         v[dr]=v[st];
  33.     }
  34.     v[st]=x;
  35.     return st;
  36. }
  37. void qSort(int st, int dr)
  38. {
  39.     //sorteaza elementele a[st],....,a[dr]
  40.     int m=divide(st,dr);
  41.     if(m-1>st)
  42.         qSort(st,m-1);
  43.     if(m+1<dr)
  44.         qSort(m+1,dr);
  45. }
  46. int main()
  47. {
  48.     citire();
  49.     qSort(1,n);
  50.     afisare();
  51.     return 0;
  52. }
Advertisement
Add Comment
Please, Sign In to add comment