Probably the easiest understandable quick sort and quick select so far. ... I like this code!.
#include <vector>
#include <iostream>
using namespace std;
int qSelect(vector<int>& nums, int first, int last) {
int pivot = nums[first];
int p = first; // use two pointer. P always points to be one less than pivot.
for(int i = first + 1; i <= last; ++i) {
if(nums[i] < pivot) {
p++;
swap(nums[i], nums[p]);
}
}
swap(nums[p], nums[first]);
return p;
}
void qSort(vector<int>& nums, int first, int last) {
int pivotIndex;
if(first < last) {
pivotIndex = qSelect(nums, first, last);
qSort(nums, first, pivotIndex - 1);
qSort(nums, pivotIndex + 1, last);
}
}
void qSort(vector<int>& nums) {
qSort(nums, 0, nums.size() - 1);
}
int main(void) {
vector<int> nums{7, -13, 1, 3, 10, 5, 2, 4};
qSort(nums, 0, 7);
for(int i = 0; i < nums.size(); ++i) {
cout << nums[i] << endl;
}
}