All Posts All Posts

Zero-Swap Sorting Google Interview Question

March 29, 2018·
CS Theory
·1 min read
Tecker Yu
Tecker Yu
AI Native Cloud Engineer × Part-time Investor

Question:

An array of length n contains numbers 0 to n-1 in random order. Now you can only perform swaps between 0 and other numbers. Please sort this array.

package main

import "fmt"

func main() {
    s := []int{3, 5, 4, 0, 1, 2, 6}
    for _, v := range s {
        fmt.Printf("%d ", v)
    }
    fmt.Printf("\nafter:\n")

    var i int
    // First find 0 and put it at the first position
    for s[i] != 0 {
        i++
    }
    s[0], s[i] = s[i], s[0]

    i = 1

    for {
        // Starting from index 1, swap s[i] with 0 to move number x to position s[x]
        for s[i] != i {
            s[s[i]], s[0] = s[0], s[s[i]]
            s[i], s[s[i]] = s[s[i]], s[i]
            // Remember to swap 0 back to its original position each time
            s[i], s[0] = s[0], s[i]
        }
        if i == len(s)-1 {
            break
        }
        // After sorting s[i], proceed to sort s[i+1]
        i++
    }

    for _, v := range s {
        fmt.Printf("%d ", v)
    }
}

Run Code Online

Views