[Python]でクイックソート♪

1.コード

def qck_sort(iterable):
    less_list = []
    greater_list = []
    if len(iterable) < 2:
        return iterable
    else:
        pivot = iterable[0]
        for ele in iterable[1:]:
            if ele <= pivot:
                less_list.append(ele)
            elif ele > pivot:
                greater_list.append(ele)
        return qck_sort(less_list) + [pivot] + qck_sort(greater_list)

"""
ex.
[5, 3, 4, 10]

less 3, 4 | pivot 5 | greater 10
    |                       |
    | qck_sort()            \/qck_sort()
    \/                   return[10]
less [] | pivot 3 | greater 4
    | qck_sort()       | qck_sort()
    \/                 \/
    return []         return [4]     
return [3, 4]

=> [3, 4] + [5] + [10]
=> [3, 4, 5, 10]
"""

if __name__ == "__main__":
    result = qck_sort([5, 3, 4, 10])
    print(result)

2.実行結果

[3, 4, 5, 10]

いいなと思ったら応援しよう!