Python Program to Sort an array of 0s, 1s and 2s

Given an array A[] consisting 0s, 1s and 2s. The task is to write a function that sorts the given array. The functions should put all 0s first, then all 1s and all 2s in last.

Examples:

Input : {0, 1, 2, 0, 1, 2, 2, 2, 2, 1}
Output : {0, 0, 1, 1, 1, 2, 2, 2, 2, 2}

Input :  {0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1}
Output :  {0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2}

Simple Solution : We create three empty lists. We add all 0s to first list, 1s to second list and 2s to third list. Finally we append all lists and return

filter_none

edit
close

play_arrow

link
brightness_4
code

# Function for sort
def SortWithoutSorting(arr):
# 3 Empty list for initialize 0 1 and 2
  
    l1 =[]
    l2 =[]
    l3 =[]
    for i in range(len(arr)):
        if arr[i] == 0:
            l1.append(arr[i])
        elif arr[i] == 1:
            l2.append(arr[i])
        else:
            l3.append(arr[i])
    return (l1 + l2 + l3)
  
# Driver Code
arr = array.array('i', [0, 1, 0, 1, 2, 2, 0, 1])
print(SortWithoutSorting(arr)) 

chevron_right


Efficient Solution The above solution requires extra space. How to do it without extra space (in-place) in the same given list and using only one traversal. Please refer Sort an array of 0s, 1s and 2s for implementation of the efficient solution.

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.