Skip to content

Instantly share code, notes, and snippets.

@shotarok
Last active December 16, 2015 03:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shotarok/5367231 to your computer and use it in GitHub Desktop.
Save shotarok/5367231 to your computer and use it in GitHub Desktop.
Quick sort where space order is O(1)
# coding: utf-8
import random
def quick_sort(inlist, first, last):
if last - first < 1:
return inlist
pivot = inlist[first]
left, right = first, last
while left != right:
if inlist[right] >= pivot:
right -= 1
elif inlist[left] < pivot:
left += 1
else:
inlist[right], inlist[left] = inlist[left], inlist[right]
# right equals left
middle = right
inlist = quick_sort(inlist, first, middle)
inlist = quick_sort(inlist, middle+1, last)
return inlist
@shotarok
Copy link
Author

これ、pivotにとった数が複数あると無限ループになりそうですね。

@yasuharu519
Copy link

なっちゃいそうだね。

    if inlist[right] >= pivot:
        right -= 1
    elif inlist[left] < pivot:
        left += 1

ってだけで、うまくいくと思う

@shotarok
Copy link
Author

update しました。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment