def swap(array, a_index, b_index): temp = array[a_index] array[a_index] = array[b_index] array[b_index] = temp def qsortArray(array, left, right): if (left >= right): return last = left for i in range(left, right+1): if (array[i] < array[left]): last += 1 swap(array, i, last) swap(array, left, last) qsortArray(array, left, last-1) qsortArray(array, last+1, right) def QsortArray(array, first_index, end_index): if first_index >= end_index: return last_index = first_index for i in range(first_index, end_index+1): if array[i] < array[first_index]: last_index += 1 swap(array, i, last_index) swap(array, first_index, last_index) QsortArray(array, first_index, last_index-1) QsortArray(array, last_index+1, end_index) # border is the index that begins the numbers greater than pivot. # the following qsort implementation uses the last number in the # subarray as the pivot. def partition(array, first, last): border = first for cursor in xrange(first, last): if array[cursor] < array[last]: swap(array, border, cursor) border += 1 swap(array, border, last) return border def qsort(array, first, last): if (first<last): pivot = partition(array, first, last) qsort(array, first, pivot-1) qsort(array, pivot+1, last) ar = [5, 8, 7, 6, 9, 4, 3, 2, 1] QsortArray(ar, 0, 8) print ar ar = [5, 8, 7, 6, 9, 4, 3, 2, 1] qsort(ar, 0, 8) print ar
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