C++ Online Compiler
Example: Quick Sort in C++ in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// Quick Sort in C++ #include <iostream> #include <vector> // Using std::vector for dynamic array #include <algorithm> // For std::swap // Function to swap two elements void swap(int* a, int* b) { int t = *a; *a = *b; *b = t; } /* This function takes 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]; // Pivot is the last element 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 swap(&arr[i], &arr[j]); } } 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 i = 0; i < arr.size(); i++) { std::cout << arr[i] << " "; } 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(); // Step 2: Print the original array std::cout << "Original array: "; printArray(arr); // Step 3: Apply Quick Sort quickSort(arr, 0, n - 1); // Step 4: Print the sorted array std::cout << "Sorted array: "; printArray(arr); return 0; }
Output
Clear
ADVERTISEMENTS