How to sort 0s 1s & 2s for an array in swift?

[Question]: In a given array sort all 0s 1s & 2s .For example: I/P {0, 1, 2, 0, 1, 2} o/p:: {0, 0, 1, 1, 2, 2}
Solution:- We can use three pointers low, mid & high. Where low & mid is start index(i.e. 0) & high is arrayLength – 1. In a while loop we traverse mid to high & exit from loop when    while mid <= high {
Special Note: We swap from Low (0) & High(2) As simple as that. So we don’t move 1s & it by default will be in middle.

func sortColors(_ nums: inout [Int]) {
    var low = 0
    var high = nums.count - 1
    var mid = 0
    
    while mid <= high {
        switch nums[mid] {
        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 nums = [2,0,2,1,1,0]
sortColors(&nums)
print("sort--->", nums)// prints.  [0, 0, 1, 1, 2, 2]

Leave a Comment

Your email address will not be published. Required fields are marked *