Randomized Quickselect
Tutorial Video
Text description (accessibility)
This video demonstrates the "Randomized Quickselect" functional Rust example. Difficulty level: Fundamental. Key concepts covered: Functional Programming. Finding the kth smallest element in an unsorted array naively requires sorting: O(n log n). Key difference from OCaml: | Aspect | Rust | OCaml |
Tutorial
The Problem
Finding the kth smallest element in an unsorted array naively requires sorting: O(n log n). Quickselect finds it in O(n) expected time by using the partition step from quicksort but only recursing into one side. Choosing the pivot randomly avoids worst-case O(n^2) behavior from adversarial inputs. Practical uses: computing medians for statistics, percentile calculations in monitoring systems, streaming data analysis (p99 latency), and machine learning (median-based normalization). The deterministic variant (median-of-medians) guarantees O(n) worst-case but with higher constants.
🎯 Learning Outcomes
Code Example
#![allow(clippy::all)]
//! PlaceholderKey Differences
| Aspect | Rust | OCaml |
|---|---|---|
| In-place | &mut [i32] slice partitioned | array mutation or copy |
| Random pivot | rand::thread_rng() | Random.int n |
| Three-way match | match pivot_pos.cmp(&k) | compare pivot_pos k \|> match |
| Rank adjustment | k - pivot_pos - 1 | Same arithmetic |
| Worst case | O(n^2) with bad pivots | Same |
| Deterministic | Median-of-medians variant | Same |
OCaml Approach
OCaml's quickselect uses Array.swap for the Lomuto partition. Random.int n provides the random pivot. The recursive call on a sub-array uses Array.sub (copying) or passes array bounds explicitly. OCaml's compare on the pivot position drives the three-case match. The functional style returns the kth element without modifying the array by working on a copy; the in-place version uses Array.blit for subarray passing.
Full Source
#![allow(clippy::all)]
//! PlaceholderDeep Comparison
OCaml vs Rust: Randomized Quickselect
Overview
See the example.rs and example.ml files for detailed implementations.
Key Differences
| Aspect | OCaml | Rust |
|---|---|---|
| Type system | Hindley-Milner | Ownership + traits |
| Memory | GC | Zero-cost abstractions |
| Mutability | Explicit ref | mut keyword |
| Error handling | Option/Result | Result<T, E> |
See README.md for detailed comparison.