[Question]: How to sort an array which has 0s, 1s and 2s
Approach #1 Using Dutch National Flag
I used three pointers low mid & high The sorting of 0,1,2 is as per below steps
arr[0….low-1] contains 0. [most left part]
arr[low….mid-1] contains 1
arr[high+1….n-1] contains 2. [most right part],
So we swap according to the left(0) mid(1) & hight(2) position
func sortZerosOnesTwos(nums: inout [Int]) {
var low = 0
var high = nums.count - 1
var mid = 0
while mid <= high {
let item = nums[mid]
switch item {
case 0:
nums.swapAt(low,mid)
low += 1
mid += 1
case 2:
nums.swapAt(mid,high)
high -= 1
case 1:
mid += 1
default:
continue
}
}
}
var miscArray = [0,2,0,2,1,1]
sortZerosOnesTwos(nums: &miscArray)
print("After sorting 0's, 1's, 2's", miscArray) //[0, 0, 1, 1, 2, 2]