LoginSignup
9
9

More than 5 years have passed since last update.

pythonでquicksort

Posted at

Learn You Haskell for Great Goodに出てくるquicksortを,リスト内包や再帰もそのままでpythonで作成。ただそれだけなんだけど,いつか何かの役に立つかもしれないので一応残しておこう。

def quicksort(x):
    if x==[]: return []

    smallerSorted = quicksort([a for a in x[1:] if a <= x[0]])
    biggerSorted = quicksort([a for a in x[1:] if a > x[0]])

    return(smallerSorted+[x[0]]+biggerSorted)

x = [10,2,5,3,1,6,7,4,2,3,4,8,9]
print(quicksort(x))

実行結果

[1, 2, 2, 3, 3, 4, 4, 5, 6, 7, 8, 9, 10]
9
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
9