Randomized Quicksort Implementation

Chengyuan Pan

Randomized Quicksort Implementation:
Selecting a Random Pivot to Ensure Time Complexity

By choosing the pivot uniformly at random for each partition, we avoid consistently bad splits on already structured input and obtain an expected time complexity of O(nlogn) with high probability.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include<iostream>
#include<vector>

using namespace std;

int partition(vector<int>& arr, int l, int r) {
int pivot = arr[r];
int i = l;
for (int j = l; j < r; j++) {
if (arr[j] <= pivot) {
swap(arr[i++], arr[j]);
}
}
swap(arr[i], arr[r]);
return i;
}

int randomPartition(vector<int>& arr, int l, int r) {
int pivotPos = (random() % (r - l + 1) + l);
swap(arr[pivotPos], arr[r]);
return partition(arr, l, r);
}

void quichRank(vector<int>& arr, int l, int r) {
if (l <= r) {
int pivotPos = randomPartition(arr, l, r);
quichRank(arr, l, pivotPos - 1);
quichRank(arr, pivotPos + 1, r);
}
}

int main() {
vector<int> arr;
for (int i = 0; i < 10; i++) {
arr.push_back(random()%100);
}
quichRank(arr, 0, arr.size() - 1);
for (auto num : arr) {
cout << num << " ";
}
return 0;
}
  • Title: Randomized Quicksort Implementation
  • Author: Chengyuan Pan
  • Created at : 2026-03-16 00:00:00
  • Updated at : 2026-03-17 12:05:29
  • Link: https://chengyuanpan.github.io/2026/03/16/2026-03-16-randomized-quicksort-implementation/
  • License: This work is licensed under CC BY-NC-SA 4.0.
Comments
On this page
Randomized Quicksort Implementation