Advertisement
fattboy

Quick Sort

Mar 9th, 2015
205
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.40 KB | None | 0 0
  1. #include <iostream>
  2. #include <conio.h>
  3. #include <iomanip>
  4.  
  5. using namespace std;
  6.  
  7. void Quick_Sort(int *a, int left, int right)
  8. {
  9.         if (left<right)
  10.         {
  11.             int i = left;
  12.             int j = right;
  13.             int k = (left+right)/2;
  14.             int t = a[k];
  15.             while (i<=j)
  16.             {
  17.                 while (a[i]<t) i=i+1;
  18.                 while (a[j]>t) j=j-1;
  19.                 if (i <= j)
  20.                 {
  21.                     int tg = a[i];
  22.                     a[i] = a[j];
  23.                     a[j] = tg;
  24.                     i++; j--;
  25.                 }
  26.             }
  27.             Quick_Sort(a,left,j);   // j la right
  28.             Quick_Sort(a,i,right);  // i la left
  29.         }
  30. }
  31.  
  32.  
  33. void in(int n, int *p)
  34. {
  35.     for (int i=0; i<n; i++)
  36.     cout << setw(6) << p[i];
  37. }
  38.  
  39. main()
  40. {
  41.     int n;
  42.     int i,j;
  43.     int m, k, t, tg;
  44.     int *a;
  45.     do {
  46.         cout << "Nhap n: "; cin >> n;
  47.     }while (n<=0);
  48.    
  49.     a = new int[n];
  50.    
  51.     for (i=0; i<n; i++)
  52.     {
  53.         cout << "Nhap a[" << i+1 << "]: ";
  54.         cin >> a[i];
  55.     }
  56.    
  57.     cout << "Day da nhap: " << endl;
  58.     in(n,a);
  59.    
  60.     //sx
  61.     /*
  62.     for (i=0; i<n; i++)
  63.     {
  64.         j = i;
  65.         m = a[i+1];
  66.         while(j>-1 && a[j]>m)
  67.         {
  68.             a[j+1]=a[j];
  69.             --j;
  70.         }
  71.         a[j+1] = m;
  72.     }
  73.     */
  74.    
  75.     /*
  76.     for (i=0; i<n-1; i++)
  77.     for (j=n-1; j>i; j--)
  78.     {
  79.         if (a[j] < a[j-1]) {
  80.             tg = a[j];
  81.             a[j] = a[j-1];
  82.             a[j-1] = tg;
  83.         }
  84.     }
  85.     */
  86.     /*
  87.     for (i=0; i<n-1; i++)
  88.     {
  89.         m = i;
  90.         for (j=i+1; j<n; j++)
  91.         if (a[j]<a[m]) m=j;
  92.         if (i!=m)
  93.         {tg = a[i]; a[i]= a[m]; a[m]=tg;}
  94.     }
  95.    
  96.     */
  97.     Quick_Sort(a,0,n-1);
  98.    
  99.    
  100.     cout << endl << "Day da sx: " << endl;
  101.     in(n,a);
  102.     getch();
  103. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement