Advertisement
Araf_12

Quick Sort

Jan 4th, 2023 (edited)
10
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.51 KB | None | 0 0
  1. #include <iostream>
  2. #include <algorithm>
  3. using namespace std;
  4.  
  5. // Function to partition the array on the basis of pivot element
  6. int partition(int *arr, int low, int high)
  7. {
  8.     // Select the pivot element
  9.     int pivot = arr[high];
  10.  
  11.     // Index of smaller element
  12.     int i = low - 1;
  13.  
  14.     // Traverse the array and swap elements
  15.     for (int j = low; j <= high - 1; j++)
  16.     {
  17.         // If current element is smaller than or equal to pivot
  18.         if (arr[j] <= pivot)
  19.         {
  20.             i++;
  21.             swap(arr[i], arr[j]);
  22.         }
  23.     }
  24.  
  25.     // Swap the pivot element with the element at index i+1
  26.     swap(arr[i + 1], arr[high]);
  27.     return i + 1;
  28. }
  29.  
  30.  
  31.  
  32.  
  33. // Function to implement QuickSort
  34. // arr - array to be sorted
  35. // low - starting index
  36. // high - ending index
  37. void QuickSort(int *arr, int low, int high)
  38. {
  39.     // Base case
  40.     if (low < high)
  41.     {
  42.         // Partition the array around the pivot element
  43.         int pivot_index = partition(arr, low, high);
  44.  
  45.         // Recursively sort the subarrays on either side of the pivot element
  46.         QuickSort(arr, low, pivot_index - 1);
  47.         QuickSort(arr, pivot_index + 1, high);
  48.     }
  49. }
  50.  
  51.  
  52.  
  53. int main()
  54. {
  55.     // Array to be sorted
  56.     int arr[] = {5, 2, 8, 1, 9, 3};
  57.  
  58.     // Get the size of the array
  59.     int n = sizeof(arr) / sizeof(arr[0]);
  60.  
  61.     // Sort the array
  62.     QuickSort(arr, 0, n - 1);
  63.  
  64.     // Print the sorted array
  65.     for (int i = 0; i < n; i++)
  66.         cout << arr[i] << " ";
  67.  
  68.     return 0;
  69. }
  70.  
Tags: Quick Sort
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement