fuliver123

Quick_Sort

May 15th, 2016
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.55 KB | None | 0 0
  1. #include<iostream>
  2. #include<ctime>
  3. #include<cstdlib>
  4.  
  5. using namespace std;
  6.  
  7. int ran(int a1, int a2)
  8. {
  9.     return rand() % (a2 - a1 + 1) + a1;
  10. }
  11.  
  12. int swap(int &a, int &b)
  13. {
  14.     int temp = a; a = b; b = temp;
  15. }
  16.  
  17. int Partition(int *arr, int left, int right)
  18. {
  19.     int i = left, j = right;
  20.     int pivot = ran(left, right);
  21.     do
  22.     {
  23.         while (i == pivot || arr[i]<=arr[pivot]) i++;
  24.         while (j == pivot || arr[j]>=arr[pivot]) j--;
  25.         if (i<j)
  26.         {
  27.             swap(arr[i], arr[j]);
  28.             i++;
  29.             j--;
  30.         }
  31.     } while (i<j);
  32.     if (j<left)
  33.     {
  34.         if ((pivot - i)*(arr[pivot] - arr[i])<0)
  35.         {
  36.             swap(arr[pivot], arr[i]);
  37.             return i;
  38.         }
  39.         return pivot;
  40.     }
  41.     else if (i>right)
  42.     {
  43.         if ((pivot - j)*(arr[pivot] - arr[j])<0)
  44.         {
  45.             swap(arr[pivot], arr[j]);
  46.             return j;
  47.         }
  48.         return pivot;
  49.     }
  50.     if ((pivot - i)*(arr[pivot] - arr[i])<0)
  51.     {
  52.         swap(arr[pivot], arr[i]);
  53.         return i;
  54.     }
  55.     else if ((pivot - j)*(arr[pivot] - arr[j])<0)
  56.     {
  57.         swap(arr[pivot], arr[j]);
  58.         return j;
  59.     }
  60.     else
  61.         return pivot;
  62. }
  63.  
  64. void quickSort(int *arr, int left, int right)
  65. {
  66.     if (left<right)
  67.     {
  68.         int p = Partition(arr, left, right);
  69.         if (left<p)
  70.             quickSort(arr, left, p - 1);
  71.         if (right>p)
  72.             quickSort(arr, p + 1, right);
  73.     }
  74. }
  75.  
  76. int main()
  77. {
  78.     srand((unsigned)(time(NULL)));
  79.     int i, arr[20] = {};
  80.     for (i = 0; i<20; i++)
  81.         arr[i] = ran(1, 1000);
  82.     cout << "Before " << endl;
  83.     for (i = 0; i<20; i++)
  84.         cout << arr[i] << " ";
  85.     cout << endl;
  86.     quickSort(arr, 0, 19);
  87.     cout << "After " << endl;
  88.     for (i = 0; i<20; i++)
  89.         cout << arr[i] << " ";
  90.     cout << endl;
  91.     return 0;
  92. }
Advertisement
Add Comment
Please, Sign In to add comment