Algorithm Steps
- Given an array
arr
consisting only of 0s, 1s, and 2s. - Initialize three pointers:
low = 0
,mid = 0
, andhigh = n - 1
. - Traverse the array with
mid
pointer until it exceedshigh
: - → If
arr[mid] == 0
, swaparr[low]
andarr[mid]
, increment bothlow
andmid
. - → If
arr[mid] == 1
, just movemid
one step ahead. - → If
arr[mid] == 2
, swaparr[mid]
andarr[high]
, and decrementhigh
. - Continue until the array is sorted.
Sort 0s, 1s, and 2s in Array using Dutch National Flag Algorithm Code
Python
JavaScript
Java
C++
C
def sort_colors(arr):
low, mid, high = 0, 0, len(arr) - 1
while mid <= high:
if arr[mid] == 0:
arr[low], arr[mid] = arr[mid], arr[low]
low += 1
mid += 1
elif arr[mid] == 1:
mid += 1
else:
arr[mid], arr[high] = arr[high], arr[mid]
high -= 1
return arr
# Sample Input
arr = [2, 0, 2, 1, 1, 0]
print("Sorted Array:", sort_colors(arr))