Advertisement
maya97

LAB_ONE

Dec 25th, 2019
728
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.50 KB | None | 0 0
  1. #include<iostream>
  2. using namespace std;
  3.  
  4.  
  5. int partition1(int arr[], int l, int h)
  6. {
  7.     int p = arr[l];
  8.     int i = l;
  9.     int j = h;
  10.     while (i < j)
  11.     {
  12.         do
  13.         {
  14.             i++;
  15.         } while (arr[i] <= p);
  16.         do
  17.         {
  18.             j--;
  19.         } while (arr[j] > p);
  20.  
  21.         if (i < j)
  22.             swap(arr[i], arr[j]);
  23.     }
  24.     swap(arr[l], arr[j]);
  25.     return j;
  26. }
  27.  
  28. void quickSort1(int arr[], int l, int h)
  29. {
  30.  
  31.     if (l < h) {
  32.         int piv = partition1(arr, l, h);
  33.         quickSort1(arr, l, piv);
  34.         quickSort1(arr, piv + 1, h);
  35.     }
  36.  
  37. }
  38.  
  39.  
  40.  
  41. int partition2(int arr[], int iBegin, int jEnd) {
  42.     int i = iBegin;
  43.     int j = jEnd;
  44.     int pivLoc = i;
  45.     while (true)
  46.     {
  47.         while (arr[pivLoc] <= arr[j] && pivLoc != j)
  48.         {
  49.             j--;
  50.         }
  51.         if (pivLoc == j)
  52.             break;
  53.         else if (arr[pivLoc] > arr[j])
  54.         {
  55.             swap(arr[j], arr[pivLoc]);
  56.             pivLoc = j;
  57.         }
  58.  
  59.         while (arr[pivLoc] >= arr[i] && pivLoc != i)
  60.         {
  61.             i++;
  62.         }
  63.         if (pivLoc == i)
  64.             break;
  65.         else if (arr[pivLoc] < arr[i])
  66.         {
  67.             swap(arr[i], arr[pivLoc]);
  68.             pivLoc = i;
  69.         }
  70.     }
  71.     return pivLoc;
  72. }
  73.  
  74.  
  75. void quickSort2(int arr[], int l, int h)
  76. {
  77.  
  78.     if (l < h) {
  79.         int piv = partition2(arr, l, h);
  80.         quickSort2(arr, l, piv - 1);
  81.         quickSort2(arr, piv + 1, h);
  82.     }
  83.  
  84. }
  85.  
  86.  
  87. int main()
  88. {
  89.     int arr[] = { 2,-1,4,7,0 };
  90.    
  91.     for (int i = 0; i < 5; i++)
  92.     {
  93.         cout << arr[i] << " ";
  94.     }
  95.    
  96.     cout << endl;
  97.     int n = sizeof(arr) / sizeof(arr[0]);
  98.  
  99.     quickSort2(arr, 0, n - 1);
  100.    
  101.     cout << "the sorted array is : \n";
  102.     for (int i = 0; i < n; i++)
  103.     {
  104.         cout << arr[i] << " ";
  105.     }
  106.  
  107.     return 0;
  108. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement