i have implemented the quick select algorithm.
i have the problem that my algorithm ends up in a endless loop, when i use duplicates in the array...
can you help me to get it work?
the expected complexity is O(n) with worst case O(n^2)?
#include <iostream>
#include <vector>
#include <algorithm>
#include <ctime>
using namespace std;
int rand_partition(vector<int> &a, int left, int right) {
int pivotIndex = left + (rand() % (right - left));
//int m = left + (right - left) / 2; //... to test the algo...no rand at this point
int pivot = a[pivotIndex];
int i = left;
int j = right;
do {
while (a[i] < pivot) i++; // find left element > pivot
while (a[j] > pivot) j--; // find right element < pivot
// if i and j not already overlapped, we can swap
if (i < j) {
swap(a[i], a[j]);
}
} while (i < j);
return i;
}
// Returns the n-th smallest element of list within left..right inclusive (i.e. n is zero-based).
int quick_select(vector<int> &a, int left, int right, int n) {
if (left == right) { // If the list contains only one element
return a[left]; // Return that element
}
int pivotIndex = rand_partition(a, left, right);
// The pivot is in its final sorted position
if (n == pivotIndex) {
return a[n];
}
else if (n < pivotIndex) {
return quick_select(a, left, pivotIndex - 1, n);
}
else {
return quick_select(a, pivotIndex + 1, right, n);
}
}
int main() {
vector<int> vec= {1, 0, 3, 5, 0, 8, 6, 0, 9, 0};
cout << quick_select(vec, 0, vec.size() - 1, 5) << endl;
return 0;
}