
Sort an Array of 0s, 1s and 2s
Sort an Array of 0s, 1s and 2s Problem Statement Given an array consisting of only 0s, 1s and 2s, sort the array in ascending order. Examples Input arr = [0, 2, 1, 2, 0] Output [0, 0, 1, 2, 2] Input arr = [2, 0, 1] Output [0, 1, 2] Approach 1 Using Sorting The simplest way is to sort the array using built in functions. Code ```python id="sort1" def sortArray(arr): arr.sort() return arr --- ## Approach 2 Counting Method Count the number of 0s, 1s and 2s, then overwrite the array. --- ### Steps 1 Count number of 0s, 1s and 2s 2 Fill array with 0s 3 Then fill with 1s 4 Then fill with 2s --- ### Code ```python id="sort2" def sortArray(arr): count0 = arr.count(0) count1 = arr.count(1) count2 = arr.count(2) i = 0 for _ in range(count0): arr[i] = 0 i += 1 for _ in range(count1): arr[i] = 1 i += 1 for _ in range(count2): arr[i] = 2 i += 1 return arr Approach 3 Dutch National Flag Algorithm This is the most efficient method. Steps 1 Maintain three pointers low, mid and high 2 low is for 0 place
Continue reading on Dev.to
Opens in a new tab


