Move all negative to one side of array in Kotlin

To move all the negative elements to one side of an array, you can use a two-pointer approach. The idea is to maintain two pointers: one pointing to the first element of the array and the other pointing to the last element of the array. The pointer at the front moves forward until it encounters a positive element, while the pointer at the back moves backwards until it encounters a negative element. When both pointers have stopped, we swap the elements at the two pointers and continue the process until the pointers meet.

Here’s an example implementation in Kotlin:

Kotlin
fun moveNegativeElements(arr: IntArray) {
    val n = arr.size
    var left = 0
    var right = n - 1
    while (left <= right) {
        if (arr[left] < 0 && arr[right] >= 0) {
            // swap arr[left] and arr[right]
            val temp = arr[left]
            arr[left] = arr[right]
            arr[right] = temp
            // move pointers to next positions
            left++
            right--
        } else if (arr[left] >= 0) {
            // move left pointer to next position
            left++
        } else if (arr[right] < 0) {
            // move right pointer to previous position
            right--
        }
    }
}
fun main(){
    val arr = intArrayOf(-1, 2, -3, 4, 5, -6, 7, -8)
	moveNegativeElements(arr)
	println(arr.contentToString())
}

moveNegativeElements takes an IntArray as input and moves all the negative elements in the array to the left side. The function first gets the length of the array n and initializes two pointers: left pointing to the first element of the array and right pointing to the last element of the array. The function then enters a loop where it checks if the element at left is negative and the element at right is positive. If this is the case, the function swaps the elements at left and right, and moves both pointers to the next and previous positions respectively. If the element at left is positive, the function moves the left pointer to the next position. Similarly, if the element at right is negative, the function moves the right pointer to the previous position. The loop continues until the left and right pointers meet.

This code creates an integer array arr and calls the moveNegativeElements function to move all the negative elements in the array to the left side. The function then prints the modified array. The output of this code will be: [7, 2, 5, 4, -3, -6, -1, -8]

Leave a Comment