Challenge: Write Quick Sort
Completed
Sort n numbers with your own in-place quick sort using the Lomuto partition (last item as pivot).
Input
Line 1: n. Line 2: n whole numbers.
Output
The sorted numbers.
Example
Input
6 10 7 8 9 1 5
Output
1 5 7 8 9 10
Editor
C++
Hints
partition puts smaller items before the pivot and returns the pivot's final index.
Recurse on both sides.
Solution explanation
After each partition the pivot is in its final place.
Show solution
#include <iostream>
#include <vector>
using namespace std;
int part(vector<int>& a, int lo, int hi) {
int pivot = a[hi], i = lo;
for (int j = lo; j < hi; j++)
if (a[j] < pivot) swap(a[i++], a[j]);
swap(a[i], a[hi]);
return i;
}
void quickSort(vector<int>& a, int lo, int hi) {
if (lo >= hi) return;
int p = part(a, lo, hi);
quickSort(a, lo, p - 1);
quickSort(a, p + 1, hi);
}
int main() {
int n;
cin >> n;
vector<int> a(n);
for (int& x : a) cin >> x;
quickSort(a, 0, n - 1);
for (int i = 0; i < n; i++) cout << a[i] << (i + 1 < n ? " " : "\n");
return 0;
} Output
Answer
You can practice without logging in. Log in to save completion.
Save your progress
You're practising as a guest, so your progress won't be saved.
- Track every lab you complete
- Earn verifiable lab certificates
- See your progress in every module