The Dutch Flag Sort
HardAcc. 84.6%
+45 XP 20
The Dutch Flag Partition
Sorting usually requires hundreds of comparisons, but what if you only have three types of items (like the Red, White, and Blue of the Dutch Flag)? By using three pointers (low, mid, and high), you can literally "push" each item into its correct zone (0s to the left, 2s to the right, and 1s in the middle) in a single physical pass through the array.
The Assignment
Your mission is to partition the colors (0, 1, and 2). Your function receives an array nums.
- Initialize
lowandmidat index 0, andhighat the last index. - While the
midpointer has not passed thehighpointer:- If the value at
midis 0: Swap it withlow, and move both pointers forward. - If the value at
midis 1: Simply move themidpointer forward. - If the value at
midis 2: Swap it withhigh, and move thehighpointer backward.
- If the value at
- Print every number in the now-partitioned array on a new line.
01EXAMPLE 1
Input
[2,0,2,1,1,0]Output
0
0
1
1
2
2Explanation: Sorted in one pass.
Constraints
- Single pass (O(n)).
- In-place.
ArraysTwo PointersSorting
JavaScriptSystem handles I/O — write your function only
Loading...
1 Hidden
Input Arguments
nums[2,0,2,1,1,0]
Expected Output
0 0 1 1 2 2
Click RUN to test your solution