diff --git a/quick_sort.cpp b/quick_sort.cpp new file mode 100644 index 0000000..280b372 --- /dev/null +++ b/quick_sort.cpp @@ -0,0 +1,51 @@ +#include +#include + +using namespace std; + +// Function to partition the array and return the index of the pivot element +int partition(vector& 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++; + swap(arr[i], arr[j]); + } + } + swap(arr[i + 1], arr[high]); + return (i + 1); +} + +// Function to perform Quick Sort on an array +void quickSort(vector& 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() { + vector arr = {12, 11, 13, 5, 6}; + + cout << "Original array: "; + for (int num : arr) { + cout << num << " "; + } + cout << endl; + + int n = arr.size(); + + quickSort(arr, 0, n - 1); + + cout << "Sorted array: "; + for (int num : arr) { + cout << num << " "; + } + cout << endl; + + return 0; +}