#75
Medium Algorithms Sort colors
Array Two Pointers Sorting
69.2% acceptance
Jan 12, 2026
21433
764
Given an array nums with n objects colored red, white, or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white, and blue.
We will use the integers 0, 1, and 2 to represent the color red, white, and blue, respectively.
You must solve this problem without using the library's sort function.
Solution
Rust
Time O(n)
Space O(1)
impl Solution {
pub fn sort_colors(nums: &mut Vec<i32>) {
let mut low = 0;
let mut mid = 0;
let mut high = nums.len() - 1;
while mid <= high {
match nums[mid] {
0 => {
nums.swap(low, mid);
low += 1;
mid += 1;
},
1 => {
mid += 1;
},
_ => {
nums.swap(mid, high);
if high == 0 {
break;
}
high -= 1;
}
}
}
}
}