How to sort a slice that consists of only 0s and 1s in Go

1 Answer

0 votes
package main

import (
    "fmt"
)

// Function to sort a slice containing only 0s and 1s
func sortBinarySlice(slice []int) {
    left := 0                  // Index to track the left side
    right := len(slice) - 1      // Index to track the right side

    for left < right {
        // If the left index is at 0, move it forward
        if slice[left] == 0 {
            fmt.Println("left:", left)
            left++
        } else if slice[right] == 1 {
            // If the right index is at 1, move it backward
            fmt.Println("right:", right)
            right--
        } else {
            // If left is 1 and right is 0, swap them
            slice[left], slice[right] = slice[right], slice[left]
            fmt.Println("swap() left:", left, "right:", right)
            left++
            right--
        }
    }
}

func main() {
    // Input: Binary slice
    slice := []int{1, 0, 1, 0, 1, 0, 0, 1, 0}

    // Sort the binary slice
    sortBinarySlice(slice)

    fmt.Print("Sorted slice: ")
    for _, num := range slice {
        fmt.Print(num, " ")
    }
}




/*
run:

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

*/

 



answered Sep 3, 2025 by avibootz
...