Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 51 additions & 0 deletions quick_sort.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
#include <iostream>
#include <vector>

using namespace std;

// Function to partition the array and return the index of the pivot element
int partition(vector<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++;
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<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() {
vector<int> 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;
}