Sort Colors
To solve this coding challenge, we need to sort an array of integers representing colors (0 for red, 1 for white, and 2 for blue) in a specific order: red, white, and blue. The challenge specifically requires an in-place solution and optimally, a one-pass algorithm with constant extra space. This can be achieved using the Dutch National Flag algorithm proposed by Edsger W. Dijkstra.
Explanation
The Dutch National Flag algorithm partitions the array into three parts:- All 0's (red) on the left.
- All 1's (white) in the middle.
- All 2's (blue) on the right. We will use three pointers to achieve this:
-
pointer to track the boundary between 0's and the rest.
left -
pointer to track the boundary between 2's and the rest.
right -
pointer to go through each element in the array.
i
Initially,
-
If
is 0, swap it with the element at the
nums[i]pointer, then move bothleftandleftpointers to the right.i -
If
is 2, swap it with the element at the
nums[i]pointer, then move therightpointer to the left.right -
If
is 1, just move the
nums[i]pointer to the right.i
The loop continues until the
- Initialize pointers :
- While loop to process the array :
- End of the loop :
- Initialization :
-
Set
to 0,
leftto the last index of the array, andrightto 0.i - Iteration and swapping :
-
The loop runs as long as
is less than or equal to
i.right -
If
equals 0, the current element is a red color which should be moved to the front section. Swap this element with the element at the
nums[i]pointer and move bothleftandleftto the right.i -
If
equals 2, the element is blue which should be moved to the end section. Swap it with the element at the
nums[i]pointer and move therightpointer to the left. Do not move therightpointer because the new element at indexineeds to be checked.i -
If
equals 1, the element is white and already in the correct middle section, so simply move the
nums[i]pointer to the right.i - Completion :
- When the while loop exits, the array will be sorted in the desired order.
left
right
i
i
right
left = 0 # Initialize `left` pointer to track the boundary for 0's
right = length(nums) - 1 # Initialize `right` pointer to track the boundary for 2's
i = 0 # `i` pointer to iterate through the array
while i <= right:
if nums[i] == 0:
# Swap elements at `left` and `i`
temp = nums[left]
nums[left] = nums[i]
nums[i] = temp
# Move the `left` and `i` pointers to the right
left += 1
i += 1
elif nums[i] == 2:
# Swap elements at `right` and `i`
temp = nums[right]
nums[right] = nums[i]
nums[i] = temp
# Move the `right` pointer to the left
right -= 1
else:
# If the element is 1, just move the `i` pointer to the right
i += 1
# At this point, the array is sorted in-place with all 0's at the beginning,
# followed by 1's, and all 2's at the end.