Problem Statement: here Problem Understanding: Solution: arr = [0, 1, 2, 0, 1, 2] low = 0 mid = 0 high = 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
Jonah Blessy
Problem Statement: here
Problem Understanding:
From a given array consisting of 0s, 1s and 2s we have to arrange them in an ascending order and print the sorted array.
Solution:
arr = [0, 1, 2, 0, 1, 2]
low = 0
mid = 0
high = 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
print(arr)
In this approach, we make use of three pointers low, mid and high.
Initially, low and mid point to the first element of the array and high points to the last element of the array.
Since we want 0s to the front of array, 1s in the middle of array and 2s to the back of array, we make sure the pointer mid is lesser than pointer high.
We compare each value of the mid pointer, if arr[mid]= 0, then we interchange the index of mid and low, then increment mid and low.
If arr[mid]= 2, we move 2 to the end of the array and decrement high.
Else if arr[mid]=1, we do no operation and increment mid.
The final array will have the sorted values.
Found this useful? Share it!
Read the Full Story
Continue reading on Dev.to
Related Stories
Hiring Senior Full Stack Developer (Remote, USA)
about 2 hours ago
How I Built a Multi-Tenant WhatsApp Automation Platform Using n8n and WAHA
about 2 hours ago
I Built an Instant SEO Audit API โ Here's What I Learned About Technical SEO
about 3 hours ago
SJF4J: A Structured JSON Facade for Java
about 3 hours ago

