Menu Close

Go – Program to shift all zero to the end of array in go golang

Here, we will learn about algorithm and program of shifting all the array’s zero elements to the end of the array in go golang. There is a given array having random numbers. We have to move all the zero’s to the end of array. Time complexity is o(n) and space complexity is o(1).

Example:


Input: array = [1, 2, 0, 5, 0, 0, 3, 5]
Output: array = [1, 2, 5, 3, 5, 0, 0 ,0]

Input: array = [1, 2, 0, 0, 0, 0, 0, 2, 5]
Output: array = [1, 2, 2, 5, 0, 0, 0, 0, 0]

Algorithm:
1: Take two variable lets say index and count and initialise to 0 (zero).
2: Traverse the array using these two variables.
3: When arr[index] will not be zero, copy the value of arr[index] to arr[count] and increment both the variables by 1.
4: If arr[index] is zero then increment only index variable by 1.
5: At last, Fill the remaining array count index to zero.

For the more depth, Please follow the given below program.

Program:

package main

import (

    "fmt"

)

func main() {

    var no_of_array_ele, count int;

    fmt.Println("Enter number of elements in array: ")

    // Number of array elements
    fmt.Scan(&no_of_array_ele)

    // Create an array
    arr := make([]int, no_of_array_ele)

    // Insert the elements into array
    for index := 0; index < no_of_array_ele; index++ {

        fmt.Printf("\nEnter the %d element: ", index+1)

        fmt.Scan(&arr[index]);
    }

    count = 0

    for index := 0; index < no_of_array_ele; index++ {

        if (arr[index] != 0) {

            arr[count] = arr[index];

            count = count + 1

        }
    }

    // Fill the remaining array count index to zero
    for count != no_of_array_ele {

        arr[count] = 0;

        count = count + 1

    }

    fmt.Println("Array elements after shifting all zero to ends: \n")

    for index := 0; index < no_of_array_ele; index++ {

        fmt.Printf("%d ", arr[index])

    }
}

Enter number of elements in array: 5

Enter the 1 element: 1

Enter the 2 element: 0

Enter the 3 element: 2

Enter the 4 element: 0

Enter the 5 element: 4

Array elements before shifting all zero to ends: 
1 0 2 0 4 

Array elements after shifting all zero to ends: 
1 2 4 0 0 

For more details about golang, Please follow given below link.

Posted in algorithm, golang

Leave a Reply

Your email address will not be published.

Contact Us