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:
-
left
-
right
-
i
Initially,
-
If
nums[i]
left
left
i
-
If
nums[i]
right
right
-
If
nums[i]
i
The loop continues until the
- Initialize pointers :
- While loop to process the array :
- End of the loop :
- Initialization :
-
Set
left
right
i
- Iteration and swapping :
-
The loop runs as long as
i
right
-
If
nums[i]
left
left
i
-
If
nums[i]
right
right
i
i
-
If
nums[i]
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.