Go算法——基数排序

package main

import (
    "fmt"
)

func radixSort(array []int) {
    max := array[0]
    for i := 1; i < len(array); i++ {
        if array[i] > max {
            max = array[i]
        }
    }
    d := 1
    for max >= 10 {
        max /= 10
        d *= 10
    }
    for c := 1; c != d; c *= 10 {
        insertionSort(array, c)
    }
}

func insertionSort(array []int, d int) {
    for i := 1; i < len(array); i++ {
        key := array[i]
        j := i - 1
        for j >= 0 && array[j]/d < key/d {
            array[j+1] = array[j]
            j--
        }
        array[j+1] = key
    }
}

func main() {
    arr := []int{329, 457, 657, 839, 436, 720, 355}
    fmt.Println(arr)
    radixSort(arr)
    fmt.Println(arr)
}
image.png

你可能感兴趣的:(Go算法——基数排序)