Write a Golang program to sort a binary array in linear time


There are two methods in which we can solve this problem. Let’s check the first method.

Method 1

Examples

  • Input Array = [1, 0, 1, 0, 1, 0, 0, 1] => [0, 0, 0, 0, 1, 1, 1, 1]

Approach to solve this problem

Step 1: Define a method that accepts an array.

Step 2: Count number of 0.

Step 3: Store 0 till count becomes 0 and store 1 at the remaining indexes.

Step 4: At the end, return the array.

Program

Live Demo

package main
import "fmt"
func binarySort(arr []int) []int{
   count := 0
   for i:=0; i<len(arr); i++{
      if arr[i]==0{
         count++
      }
   }
   for j:=0; j<len(arr); j++{
      if j<count{
         arr[j] = 0
      } else {
         arr[j] = 1
      }
   }
   return arr
}

func main(){
   fmt.Println(binarySort([]int{1, 0, 1, 0, 1, 0, 0, 1}))
   fmt.Println(binarySort([]int{1, 1, 1, 1, 1, 1, 1, 1}))
   fmt.Println(binarySort([]int{0, 0, 0, 0, 0, 0, 0, 0}))
}

Output

[0 0 0 0 1 1 1 1]
[1 1 1 1 1 1 1 1]
[0 0 0 0 0 0 0 0]

Method 2

Now, let’s check the second method.

Approach to solve this problem

  • Step 1: Define a method that accepts an array.
  • Step 2: Declare the pivot element and its index j.
  • Step 3: Iterate the given array. If the element is less than pivot, then swap and increase the pivot’s index.
  • Step 4: At the end, return the array.

Program

Live Demo

package main
import "fmt"
func binarySort(arr []int) []int{
   pivot := 1
   index := 0
   for i:=0; i<len(arr); i++ {
      if arr[i]<pivot{
         arr[i], arr[index] = arr[index], arr[i]
         index++
      }
   }
   return arr
}

func main(){
   fmt.Println(binarySort([]int{1, 0, 1, 0, 1, 0, 0, 1}))
   fmt.Println(binarySort([]int{1, 1, 1, 1, 1, 1, 1, 1}))
   fmt.Println(binarySort([]int{0, 0, 0, 0, 0, 0, 0, 0}))
}

Output

[0 0 0 0 1 1 1 1]
[1 1 1 1 1 1 1 1]
[0 0 0 0 0 0 0 0]

Updated on: 04-Feb-2021

215 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements