Skip to content

Instantly share code, notes, and snippets.

@ajaysjournal
Last active July 9, 2017 17:46
Show Gist options
  • Save ajaysjournal/2bd93738a6e8ab541dbe1bfd7d95b1e2 to your computer and use it in GitHub Desktop.
Save ajaysjournal/2bd93738a6e8ab541dbe1bfd7d95b1e2 to your computer and use it in GitHub Desktop.
CLRS implementation of Quick Sort algorithm
// Quick Sort
#include <iostream>
#include <vector>
#include <iomanip>
#include <utility>
void quickSort(std::vector<int> &A, int p, int r);
int partition(std::vector<int> &A, int p, int r);
int main() {
std::vector<int> a = {2, 8, 7, 1, 3, 5, 6, 4};
std::cout << std::setw(10) << "UnSorted Array:\n"
for (int ele : a) {
std::cout << ele << std::setw(5);
}
std::cout << std::endl << std::setw(10) << "Sorted Array:\n";
quickSort(a, 0, a.size()-1);
for (int ele : a) {
std::cout << ele << std::setw(5);
}
std::cout << std::endl;
}
void quickSort(std::vector<int> &A, int p, int r) {
int q;
if ( p < r ) {
q = partition(A, p, r);
quickSort(A, p, q-1);
quickSort(A, q+1, r);
}
}
int partition(std::vector<int> &A, int p, int r) {
int x = A[r];
int i = p-1;
for (int j = p; j < r; j++) {
if (A[j] <= x) {
i = i+1;
std::swap(A[i], A[j]);
}
}
std::swap(A[i+1], A[r]);
return i+1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment