Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <algorithm>
- using namespace std;
- // Function to partition the array on the basis of pivot element
- int partition(int *arr, int low, int high)
- {
- // Select the pivot element
- int pivot = arr[high];
- // Index of smaller element
- int i = low - 1;
- // Traverse the array and swap elements
- for (int j = low; j <= high - 1; j++)
- {
- // If current element is smaller than or equal to pivot
- if (arr[j] <= pivot)
- {
- i++;
- swap(arr[i], arr[j]);
- }
- }
- // Swap the pivot element with the element at index i+1
- swap(arr[i + 1], arr[high]);
- return i + 1;
- }
- // Function to implement QuickSort
- // arr - array to be sorted
- // low - starting index
- // high - ending index
- void QuickSort(int *arr, int low, int high)
- {
- // Base case
- if (low < high)
- {
- // Partition the array around the pivot element
- int pivot_index = partition(arr, low, high);
- // Recursively sort the subarrays on either side of the pivot element
- QuickSort(arr, low, pivot_index - 1);
- QuickSort(arr, pivot_index + 1, high);
- }
- }
- int main()
- {
- // Array to be sorted
- int arr[] = {5, 2, 8, 1, 9, 3};
- // Get the size of the array
- int n = sizeof(arr) / sizeof(arr[0]);
- // Sort the array
- QuickSort(arr, 0, n - 1);
- // Print the sorted array
- for (int i = 0; i < n; i++)
- cout << arr[i] << " ";
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement