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

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

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: 2021-02-04T11:30:28+05:30

316 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements