How I Sorted an Array of 0s, 1s, and 2s in Python Without Using sort()
Introduction:
While practicing Python problems, I came across an interesting question where I had to sort an array that contains only 0s, 1s, and 2s.
The twist was that I was not allowed to use the built-in sort() function. At first, I didn’t know how to approach it, but then I learned a simple method using counting.
In this blog, I’ll explain how I solved it step by step.
Problem Statement:
We are given an array like this:
2 0 1 2 0 1 0
We need to sort it in ascending order:
0 0 0 1 1 2 2
My Idea:
Instead of sorting directly, I thought:
Why not count how many 0s, 1s, and 2s are there?
Then I can just rebuild the array using those counts.
Code I Used:
arr = list(map(int, input("Enter elements (0s,1s,2s): ").split()))
count0 = count1 = count2 = 0
for num in arr:
if num == 0:
count0 += 1
elif num == 1:
count1 += 1
else:
count2 += 1
i = 0
for i in range(count0):
arr[i] = 0
i += 1
for i in range(count1):
arr[i] = 1
i += 1
for i in range(count2):
arr[i] = 2
i += 1
print(arr)
Explanation:
First, I take input from the user
Then I count:
how many 0s
how many 1s
how many 2s
After that, I overwrite the array:
fill 0s first
then 1s
then 2s
This way, the array becomes sorted without using sort().
Example Run:
Input: arr[] = [0, 1, 2, 0, 1, 2]
Output: [0, 0, 1, 1, 2, 2]What I Learned:
Even without
sort(), we can solve problems using logicCounting technique is very useful
This problem improved my thinking skills
Conclusion:
This was a simple but interesting problem for me as a beginner. It helped me understand how to approach problems in different ways instead of always depending on built-in functions.
Comments
Post a Comment