Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<iostream>
- using namespace std;
- int partition(int arr[], int low, int high)
- {
- int pivot = arr[high];
- int i = (low - 1);
- for(int j = low; j <= high - 1; j++)
- {
- if(arr[j] <= pivot)
- {
- i++;
- int temp = arr[i];
- arr[i] = arr[j];
- arr[j] = temp;
- }
- }
- int temp = arr[i + 1];
- arr[i + 1] = arr[high];
- arr[high] = temp;
- return (i + 1);
- }
- void quickSort(int arr[], int low, int high)
- {
- if(low < high)
- {
- int pivotIndex = partition(arr, low, high);
- quickSort(arr, low, pivotIndex - 1);
- quickSort(arr, pivotIndex + 1, high);
- }
- }
- int main()
- {
- int arrSize;
- cout << "Enter the size of the array: ";
- cin >> arrSize;
- int arr[arrSize];
- cout << "Enter elements of the array: ";
- for (int i = 0; i < arrSize; ++i)
- {
- cin >> arr[i];
- }
- quickSort(arr, 0, arrSize - 1);
- cout << "Sorted array: ";
- for (int i = 0; i < arrSize; i++) {
- std::cout << arr[i] << " ";
- }
- cout << endl;
- return 0;
- }
- /*
- #include <iostream>
- // Function to partition the array into two segments and return the pivot index
- int partition(int arr[], int low, int high) {
- int pivot = arr[high]; // Choose the last element as the pivot
- int i = (low - 1); // Index of the smaller element
- for (int j = low; j <= high - 1; j++) {
- // If the current element is smaller than or equal to the pivot
- if (arr[j] <= pivot) {
- i++;
- // Swap arr[i] and arr[j]
- int temp = arr[i];
- arr[i] = arr[j];
- arr[j] = temp;
- }
- }
- // Swap arr[i + 1] and arr[high] (pivot)
- int temp = arr[i + 1];
- arr[i + 1] = arr[high];
- arr[high] = temp;
- return (i + 1);
- }
- // Function to perform Quick Sort recursively
- void quickSort(int arr[], int low, int high) {
- if (low < high) {
- // Find pivot element such that
- // element smaller than pivot are on the left and
- // elements greater than pivot are on the right
- int pivotIndex = partition(arr, low, high);
- // Recursively sort elements before and after pivot
- quickSort(arr, low, pivotIndex - 1);
- quickSort(arr, pivotIndex + 1, high);
- }
- }
- int main() {
- int arrSize;
- cout << "Enter the size of the array: ";
- cin >> arrSize;
- int arr[arrSize];
- cout << "Enter elements of the array: ";
- for(int i = 0; i < arrSize; ++i) {
- cin >> arr[i];
- }
- quickSort(arr, 0, arrSize - 1);
- cout << "Sorted array: ";
- for (int i = 0; i < arrSize; i++) {
- cout << arr[i] << " ";
- }
- cout << std::endl;
- return 0;
- }
- */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement