Convex Hull Implementation in Rust
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Convex Hull runs in O(n log n) time and O(n) space, in Rust as in every other language.
- ✓std has no geometry. The hull is a Vec<Point> over a #[derive(Clone, Copy)] struct plus slice::sort_unstable_by; for float coordinates f64::total_cmp gives the total order sort_by wants, because f64 itself is only PartialOrd and therefore has no plain sort().
- ✓The signature reviewers want is fn convex_hull(points: &[Point]) -> Vec<Point>: borrow the input, own the output, never take Vec<Point> by value just to sort it.
- ✓The Rust trap: Rust is the only language here where the same arithmetic behaves differently in your tests and in your shipped binary.
- ✓The snippet below is the plain form, and two of these are the tuning it leaves on the table.
What Convex Hull actually is
Convex Hull in Rust: what you actually reach for
Rust implementation
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]
pub struct Point {
pub x: i64,
pub y: i64,
}
#[inline]
fn cross(o: Point, a: Point, b: Point) -> i128 {
// Widen: an i64 product here overflows, which panics in debug and
// wraps silently in release.
let (ax, ay) = (a.x as i128 - o.x as i128, a.y as i128 - o.y as i128);
let (bx, by) = (b.x as i128 - o.x as i128, b.y as i128 - o.y as i128);
ax * by - ay * bx
}
fn chain(pts: impl Iterator<Item = Point>) -> Vec<Point> {
let mut h: Vec<Point> = Vec::new();
for p in pts {
while h.len() >= 2 {
let n = h.len();
if cross(h[n - 2], h[n - 1], p) > 0 {
break;
}
h.pop();
}
h.push(p);
}
h.pop();
h
}
pub fn convex_hull(points: &[Point]) -> Vec<Point> {
let mut pts = points.to_vec();
pts.sort_unstable();
pts.dedup();
if pts.len() < 3 {
return pts;
}
let mut hull = chain(pts.iter().copied());
hull.extend(chain(pts.iter().rev().copied()));
hull
}
Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe Rust-specific trap
Performance in Rust, beyond the O(n log n)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Rust type or library should I use for Convex Hull?
std has no geometry. The hull is a Vec<Point> over a #[derive(Clone, Copy)] struct plus slice::sort_unstable_by; for float coordinates f64::total_cmp gives the total order sort_by wants, because f64 itself is only PartialOrd and therefore has no plain sort(). The ecosystem answer is the geo crate: use geo::ConvexHull; brings a trait implemented for MultiPoint, LineString and Polygon, and .convex_hull() returns a Polygon<T> whose exterior ring is closed. geo-types supplies the Coord and Point primitives that the whole Rust geo stack shares, so you rarely define your own once geo is in the tree.
What is the most common Rust mistake when implementing Convex Hull?
Rust is the only language here where the same arithmetic behaves differently in your tests and in your shipped binary. (a.x - o.x) * (b.y - o.y) on i32 or i64 overflows for large coordinates, and because overflow-checks defaults to following debug-assertions, that is a panic -- attempt to multiply with overflow -- under cargo test, and a silent two's-complement wrap under cargo build --release. So the failing input aborts loudly in CI and quietly returns a mangled hull in production, which is the wrong way round. Widen the predicate to i128, or use checked_mul, or set overflow-checks = true on the release profile.
How does Convex Hull actually perform in Rust?
The snippet below is the plain form, and two of these are the tuning it leaves on the table. h[h.len() - 2] emits two bounds checks per iteration that LLVM often cannot elide, so swap the index pair for a slice pattern -- while let [.., a, b] = &h[..] { if cross(*a, *b, p) > 0 { break; } h.pop(); } -- or reach for last(). And Vec::new() grows by doubling, so Vec::with_capacity(points.len()) removes every reallocation in the scan. sort_unstable_by is pattern-defeating quicksort done in place with no scratch buffer, while the stable sort_by allocates temporary space proportional to the input. Vec::pop is a length decrement and nothing else. A Copy sixteen-byte Point stays in registers once cross inlines; behind a Box it would not. Time complexity is O(n log n) and space is O(n).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialMost AI and dev tools have a student plan. See which ones and how to claim them on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.