|
| 1 | +/* C++ implementation of QuickSort */ |
| 2 | +#include <bits/stdc++.h> |
| 3 | +using namespace std; |
| 4 | + |
| 5 | +// A utility function to swap two elements |
| 6 | +void swap(int* a, int* b) |
| 7 | +{ |
| 8 | + int t = *a; |
| 9 | + *a = *b; |
| 10 | + *b = t; |
| 11 | +} |
| 12 | + |
| 13 | +/* This function takes last element as pivot, places |
| 14 | +the pivot element at its correct position in sorted |
| 15 | +array, and places all smaller (smaller than pivot) |
| 16 | +to left of pivot and all greater elements to right |
| 17 | +of pivot */ |
| 18 | +int partition(int arr[], int low, int high) |
| 19 | +{ |
| 20 | + int pivot = arr[high]; // pivot |
| 21 | + int i |
| 22 | + = (low |
| 23 | + - 1); // Index of smaller element and indicates |
| 24 | + // the right position of pivot found so far |
| 25 | + |
| 26 | + for (int j = low; j <= high - 1; j++) { |
| 27 | + // If current element is smaller than the pivot |
| 28 | + if (arr[j] < pivot) { |
| 29 | + i++; // increment index of smaller element |
| 30 | + swap(&arr[i], &arr[j]); |
| 31 | + } |
| 32 | + } |
| 33 | + swap(&arr[i + 1], &arr[high]); |
| 34 | + return (i + 1); |
| 35 | +} |
| 36 | + |
| 37 | +/* The main function that implements QuickSort |
| 38 | +arr[] --> Array to be sorted, |
| 39 | +low --> Starting index, |
| 40 | +high --> Ending index */ |
| 41 | +void quickSort(int arr[], int low, int high) |
| 42 | +{ |
| 43 | + if (low < high) { |
| 44 | + /* pi is partitioning index, arr[p] is now |
| 45 | + at right place */ |
| 46 | + int pi = partition(arr, low, high); |
| 47 | + |
| 48 | + // Separately sort elements before |
| 49 | + // partition and after partition |
| 50 | + quickSort(arr, low, pi - 1); |
| 51 | + quickSort(arr, pi + 1, high); |
| 52 | + } |
| 53 | +} |
| 54 | + |
| 55 | +/* Function to print an array */ |
| 56 | +void printArray(int arr[], int size) |
| 57 | +{ |
| 58 | + int i; |
| 59 | + for (i = 0; i < size; i++) |
| 60 | + cout << arr[i] << " "; |
| 61 | + cout << endl; |
| 62 | +} |
| 63 | + |
| 64 | +// Driver Code |
| 65 | +int main() |
| 66 | +{ |
| 67 | + int arr[] = { 10, 7, 8, 9, 1, 5 }; |
| 68 | + int n = sizeof(arr) / sizeof(arr[0]); |
| 69 | + quickSort(arr, 0, n - 1); |
| 70 | + cout << "Sorted array: \n"; |
| 71 | + printArray(arr, n); |
| 72 | + return 0; |
| 73 | +} |
0 commit comments