Quickselect Algorithm
The Quickselect Algorithm is a highly efficient selection algorithm designed for finding the k-th smallest element in an unordered list or array. It is based on the divide and conquer principle, and shares similarities with the famous QuickSort algorithm. The primary difference between the two is that Quickselect only focuses on the part of the array that contains the desired element, whereas QuickSort sorts the entire array. As a result, Quickselect has an average-case complexity of O(n), making it faster than sorting algorithms, such as MergeSort and HeapSort, which have an average-case complexity of O(n log n).
The basic idea behind the Quickselect algorithm is to choose a "pivot" element from the array and partition the other elements into two groups - elements less than the pivot and elements greater than the pivot. If the index of the pivot is equal to the desired index k, then the pivot is the k-th smallest element. If the index of the pivot is greater than k, then the k-th smallest element lies in the left partition, and if the index of the pivot is less than k, then the k-th smallest element lies in the right partition. The algorithm then recursively repeats the process on the appropriate partition until the k-th smallest element is found. By only focusing on the relevant partition, Quickselect avoids unnecessary comparisons, which contributes to its efficient runtime.
/*
Petar 'PetarV' Velickovic
Algorithm: Quickselect
*/
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <iostream>
#include <vector>
#include <list>
#include <string>
#include <algorithm>
#include <queue>
#include <stack>
#include <set>
#include <map>
#include <complex>
#define MAX_N 1000001
using namespace std;
typedef long long lld;
int n, k;
int niz[MAX_N];
//Quickselect algoritam za nalazenje k-tog elementa u nizu
//Slozenost: O(n)
int qselect(int left, int right, int k)
{
if (left < right)
{
int pivotIndex = left;
int pivot = niz[(left+right)/2];
swap(niz[(left+right)/2], niz[right]);
for (int i=left;i<right;i++)
{
if (niz[i] < pivot)
{
swap(niz[pivotIndex], niz[i]);
pivotIndex++;
}
}
swap(niz[pivotIndex], niz[right]);
if (pivotIndex == k) return niz[pivotIndex];
else if (k < pivotIndex) return qselect(left, pivotIndex-1, k);
else return qselect(pivotIndex+1, right, k);
}
else return niz[left];
}
int main()
{
n = 5, k = 3;
niz[0] = 4;
niz[1] = 2;
niz[2] = 5;
niz[3] = 1;
niz[4] = 3;
printf("%d\n",qselect(0, n-1, k));
return 0;
}