DEV Community

Abirami Prabhakar
Abirami Prabhakar

Posted on

To Sort 0s, 1s, and 2s

So today's question deals with sorting the 0's , 1's and 2's in a array in ascending order without using the built in sort function

the given question from reference is
Given an array arr[] containing only 0s, 1s, and 2s. Sort the array in ascending order.
Input: arr[] = [0, 1, 2, 0, 1, 2]
Output: [0, 0, 1, 1, 2, 2]

Approach

Any kind of sorting can be carried out, in the previous blog post I used the Bubble sort so I intent to use a different one for this question

for this I use Selection sort -
selection sort works by finding the smallest element and swaps it with the current position

using to 2 loops

loop 1 -> entire array
loop 2 -> inside loop 1 , works i+1 elements

smallest element in from i+1 is swapped with element in i+1 by
initializing

i = min_index
as loop progresses
if arr[i+2] < arr[min_index]
min = i+2
then value at arr[i] is swapped with arr[i+2]

def selectionsort(arr):
   n = len(arr)
   for i in range (n):
       arr[min_index] = arr[i] 
       for j in range (i+1,n):
          if arr[j] < arr[min_index]:
             min_index = j
       arr[i],arr[min_index] = arr[min_index],arr[i]
       return arr

print(selectionsort([0, 1, 2, 0, 1, 2]))
Enter fullscreen mode Exit fullscreen mode

Top comments (0)