"Sort an array of 0’s, 1’s and 2’s" Code Answer's
You're definitely familiar with the best coding language Whatever that developers use to develop their projects and they get all their queries like "Sort an array of 0’s, 1’s and 2’s" answered properly. Developers are finding an appropriate answer about Sort an array of 0’s, 1’s and 2’s related to the Whatever coding language. By visiting this online portal developers get answers concerning Whatever codes question like Sort an array of 0’s, 1’s and 2’s. Enter your desired code related query in the search bar and get every piece of information about Whatever code related question on Sort an array of 0’s, 1’s and 2’s.
sort an array of 0s 1s and 2s
Approach: Count the number of 0s, 1s and 2s in the given array.
Then store all the 0s in the beginning followed by all the 1s then
all the 2s.
Algorithm:
1)Keep three counter c0 to count 0s, c1 to count 1s and c2 to count 2s
2)Traverse through the array and increase the count of c0 is the
element is 0,increase the count of c1 if the element is 1 and
increase the count of c2 if the element is 2
3)Now again traverse the array and replace first c0 elements with 0,
next c1 elements with 1 and next c2 elements with 2.
//GfG PseudoCode
Sort an array of 0’s, 1’s and 2’s
# Utility function to swap elements `A[i]` and `A[j]` in the list
def swap(A, i, j):
temp = A[i]
A[i] = A[j]
A[j] = temp
# Linear time partition routine to sort a list containing 0, 1, and 2.
# It is similar to 3–way partitioning for the Dutch national flag problem.
def threeWayPartition(A, end):
start = mid = 0
pivot = 1
while mid <= end:
if A[mid] < pivot: # current element is 0
swap(A, start, mid)
start = start + 1
mid = mid + 1
elif A[mid] > pivot: # current element is 2
swap(A, mid, end)
end = end - 1
else: # current element is 1
mid = mid + 1
All those coders who are working on the Whatever based application and are stuck on Sort an array of 0’s, 1’s and 2’s can get a collection of related answers to their query. Programmers need to enter their query on Sort an array of 0’s, 1’s and 2’s related to Whatever code and they'll get their ambiguities clear immediately. On our webpage, there are tutorials about Sort an array of 0’s, 1’s and 2’s for the programmers working on Whatever code while coding their module. Coders are also allowed to rectify already present answers of Sort an array of 0’s, 1’s and 2’s while working on the Whatever language code. Developers can add up suggestions if they deem fit any other answer relating to "Sort an array of 0’s, 1’s and 2’s". Visit this developer's friendly online web community, CodeProZone, and get your queries like Sort an array of 0’s, 1’s and 2’s resolved professionally and stay updated to the latest Whatever updates.