How to sort a list that consists of only 0s and 1s in Python

1 Answer

0 votes
# Function to sort a list containing only 0s and 1s
def sort_binary_list(arr):
    left = 0                      # Index to track the left side
    right = len(arr) - 1         # Index to track the right side

    while left < right:
        # If the left index is at 0, move it forward
        if arr[left] == 0:
            print(f"left: {left}")
            left += 1
        # If the right index is at 1, move it backward
        elif arr[right] == 1:
            print(f"right: {right}")
            right -= 1
        # If left is 1 and right is 0, swap them
        else:
            arr[left], arr[right] = arr[right], arr[left]
            print(f"swap() left: {left} right: {right}")
            left += 1
            right -= 1

# Input: Binary list
arr = [1, 0, 1, 0, 1, 0, 0, 1, 0]

# Sort the binary list
sort_binary_list(arr)

# Output the sorted list
print("Sorted list:", *arr)



"""
run:

swap() left: 0 right: 8
left: 1
right: 7
swap() left: 2 right: 6
left: 3
swap() left: 4 right: 5
Sorted list: 0 0 0 0 0 1 1 1 1

"""

 



answered Sep 2, 2025 by avibootz
...