How to sort an array that consists of only 0s and 1s in Kotlin

1 Answer

0 votes
fun sortBinaryArray(arr: IntArray) {
    var left = 0                      // Index to track the left side
    var right = arr.size - 1         // Index to track the right side

    while (left < right) {
        // If the left index is at 0, move it forward
        if (arr[left] == 0) {
            println("left: $left")
            left++
        }
        // If the right index is at 1, move it backward
        else if (arr[right] == 1) {
            println("right: $right")
            right--
        }
        // If left is 1 and right is 0, swap them
        else {
            val temp = arr[left]
            arr[left] = arr[right]
            arr[right] = temp
            println("swap() left: $left right: $right")
            left++
            right--
        }
    }
}

fun main() {
    // Input: Binary array
    val arr = intArrayOf(1, 0, 1, 0, 1, 0, 0, 1, 0)

    // Sort the binary array
    sortBinaryArray(arr)

    // Output the sorted array
    print("Sorted array: ")
    for (num in arr) {
        print("$num ")
    }
}



/*
run:

swap() left: 0 right: 8
left: 1
right: 7
swap() left: 2 right: 6
left: 3
swap() left: 4 right: 5
Sorted array: 0 0 0 0 0 1 1 1 1

*/

 



answered Sep 3 by avibootz
...