Move all negative elements to end in golang

Go program for Move all negative elements to end. Here mentioned other language solution.

package main
import "fmt"
// GoLang program for
// Move all negative elements at the end of array

// Display array elements
func display(arr[] int, n int) {
    for i := 0 ; i < n ; i++ {
        fmt.Print("  ", arr[i])
    }
    fmt.Println()
}

// Swap the given array elements
func swap(arr[] int, start int, end int) {
    var temp int = arr[start]
    arr[start] = arr[end]
    arr[end] = temp
}

// Method which is move negative elements
func moveNegative(arr[] int, n int) {
    // first index
    var i int = 0
    // last index
    var j int = n - 1
    for (i < j) {
        if arr[i] < 0 && arr[j] >= 0 {
            // When [i] index are have negative value 
            // And [j] is positive then swapping elements values
            swap(arr, i, j)
            // Modified index
            i++
            j--
        } else if arr[i] >= 0 {
            // When element of [i] is not negative
            i++
        } else {
            j--
        }
    }
}
func main() {
    // Array which are containing positive and negative values
    var arr = [] int {
        1,
        -1,
        3,
        2,
        -7,
        -5,
        11,
        6,
    }
    var n int = len(arr)
    fmt.Println("Before Arrange : ")
    // Before move element
    display(arr, n)
    // Move negative elements
    moveNegative(arr, n)
    // After arrange
    fmt.Println("After Arrange : ")
    // After move element
    display(arr, n)
}

Output

Before Arrange :
  1
  -1
  3
  2
  -7
  -5
  11
  6

After Arrange :
  1
  6
  3
  2
  11
  -5
  -7
  -1



Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment







© 2022, kalkicode.com, All rights reserved