...

/

Solution: Arrange a Binary List

Solution: Arrange a Binary List

In this review lesson, we give a detailed analysis of how to sort a binary list.

Solution #1: bubble sort

def sort_binary_list(lst):
"""
A function to sort binary list
:param lst: A list containing binary numbers
:return: A sorted binary list
"""
size = len(lst) # Store the size of list
for i in range(size):
for j in range(0, size - i - 1):
# traverse the list from 0 to size - i - 1
# Swap if the element found is greater than the next element
if lst[j] > lst[j + 1]:
lst[j], lst[j + 1] = lst[j + 1], lst[j]
return lst
# Driver to test above code
if __name__ == '__main__':
lst = [1, 0, 1, 0, 1, 0, 1, 0]
result = sort_binary_list(lst)
print(result)

Explanation

The most obvious solution to this problem is the bubble sort algorithm. All the elements in the list are either zeros or ones. Sorting the elements in an ascending order with the help of the bubble sort algorithm will shift all the zeros towards the left and all the ones towards the right.

Time complexity

...

Access this course and 1400+ top-rated courses and projects.