高速ソートアルゴリズムの実装(GolangとPython)

1371 ワード

Pythonの1行のコードは速い列を完成します
QuickSort = lambda X: [] if len(X) == 0 else QuickSort([i for i in X if i < X[0]]) + [X[0]] + QuickSort([i for i in X if i > X[0]])

Pythonクイックソート
def quick_sort(arr):

    if len(arr) <= 1:
        return arr

    mark = arr[random.randint(0, len(arr) - 1)]
    low_part = []
    mid_part = []
    hih_part = []

    for x in arr:
        if x < mark:
            low_part.append(x)
        if x == mark:
            mid_part.append(x)
        if x > mark:
            hih_part.append(x)

    low_part = quick_sort(low_part)
    hih_part = quick_sort(hih_part)

    res = low_part + mid_part + hih_part

    return res


Golangクイックソート
func QuickSort(s []int) []int {

    if len(s) <= 1{
        return s
    }

    mark := s[rand.Intn(len(s))]
    var lowPart []int
    var midPart []int
    var hihPart []int

    for _, x :=range s{
        switch  {
        case  x < mark:
            lowPart = append(lowPart, x)
        case x == mark:
            midPart = append(midPart, x)
        case x > mark:
            hihPart = append(hihPart, x)
        }
    }

    lowPart = QuickSort(lowPart)
    hihPart = QuickSort(hihPart)

    var res []int
    res = append(lowPart, midPart...)
    res = append(res, hihPart...)

    return res
}