from random import randint, randrange def Partition(A, l, r): pivot_index = randint(l, r) # get a random Pivot pivot = A[pivot_index] A[l], A[pivot_index] = A[pivot_index], A[l] # swap piwot with most left element i = l + 1 for j in range(l+1,r+1): if A[j] < pivot: # Found element less than a pivot if j != i: # part of the array with elements > pivot is empty, so there is no need to swap A[i], A[j] = A[j], A[i] i += 1 if l != i - 1: # do not swap pivot with itself A[i-1], A[l] = A[l], A[i-1] return i - 1 def QuickRange(A, p, n): if n - p < 2: return A split = Partition(A, p, len(A)-1) QuickRange(A, p, split) QuickRange(A, split + 1, n) return A def QuickSortInPlace(A): return QuickRange(A, 0, len(A)-1) def qsort(lst): if lst == []: return [] else: ran = randrange(len(lst)) lst[0], lst[ran] = lst[ran], lst[0] piv = lst[0] lesser = qsort([ l for l in lst[1:] if l < piv ]) greater = qsort([ g for g in lst[1:] if g >= piv ]) return lesser + [piv] + greater A = [4,2,1,7] qsort(A) print(A)
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question