C++ Online Compiler
Example: Quick Sort Implementation in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// Quick Sort Implementation #include <iostream> #include <vector> #include <algorithm> // For std::swap // Function to partition the array // It takes the last element as pivot, places the pivot element at its correct position // in sorted array, and places all smaller (than pivot) to left of pivot // and all greater elements to right of pivot. int partition(std::vector<int>& arr, int low, int high) { int pivot = arr[high]; // Choosing the last element as pivot int i = (low - 1); // Index of smaller element for (int j = low; j <= high - 1; j++) { // If current element is smaller than or equal to pivot if (arr[j] <= pivot) { i++; // Increment index of smaller element std::swap(arr[i], arr[j]); } } std::swap(arr[i + 1], arr[high]); return (i + 1); } // The main function that implements QuickSort // arr[] --> Array to be sorted, // low --> Starting index, // high --> Ending index void quickSort(std::vector<int>& arr, int low, int high) { if (low < high) { // pi is partitioning index, arr[pi] is now at right place int pi = partition(arr, low, high); // Separately sort elements before partition and after partition quickSort(arr, low, pi - 1); quickSort(arr, pi + 1, high); } } // Function to print an array void printArray(const std::vector<int>& arr) { for (int x : arr) { std::cout << x << " "; } std::cout << std::endl; } int main() { // Step 1: Initialize an unsorted array std::vector<int> arr = {10, 7, 8, 9, 1, 5}; int n = arr.size(); std::cout << "Original array: "; printArray(arr); // Step 2: Apply Quick Sort quickSort(arr, 0, n - 1); std::cout << "Sorted array: "; printArray(arr); // Another example std::vector<int> arr2 = {2, 8, 7, 1, 3, 5, 6, 4}; n = arr2.size(); std::cout << "\nOriginal array 2: "; printArray(arr2); quickSort(arr2, 0, n - 1); std::cout << "Sorted array 2: "; printArray(arr2); return 0; }
Output
Clear
ADVERTISEMENTS