|
1 | | -def partition(myList, start, end): |
2 | | - pivot = myList[start] |
3 | | - left = start+1 |
4 | | - # Start outside the area to be partitioned |
5 | | - right = end |
6 | | - done = False |
7 | | - while not done: |
8 | | - while left <= right and myList[left] <= pivot: |
9 | | - left = left + 1 |
10 | | - while myList[right] >= pivot and right >=left: |
11 | | - right = right -1 |
12 | | - if right < left: |
13 | | - done= True |
14 | | - else: |
15 | | - # swap places |
16 | | - temp=myList[left] |
17 | | - myList[left]=myList[right] |
18 | | - myList[right]=temp |
19 | | - # swap start with myList[right] |
20 | | - temp=myList[start] |
21 | | - myList[start]=myList[right] |
22 | | - myList[right]=temp |
23 | | - return right |
24 | | - |
25 | | -def quicksort(myList, start, end): |
26 | | - if start < end: |
27 | | - # partition the list |
28 | | - split = partition(myList, start, end) |
29 | | - # sort both halves |
30 | | - quicksort(myList, start, split-1) |
31 | | - quicksort(myList, split+1, end) |
32 | | - return myList |
33 | | - |
34 | | -def main(): |
35 | | - myList = [7,2,5,1,29,6,4,19,11] |
36 | | - sortedList = quicksort(myList,0,len(myList)-1) |
37 | | - print(sortedList) |
| 1 | +from random import randrange |
| 2 | + |
| 3 | + |
| 4 | +def partition(lst, start, end, pivot): |
| 5 | + lst[pivot], lst[end] = lst[end], lst[pivot] |
| 6 | + store_index = start |
| 7 | + for i in xrange(start, end): |
| 8 | + if lst[i] < lst[end]: |
| 9 | + lst[i], lst[store_index] = lst[store_index], lst[i] |
| 10 | + store_index += 1 |
| 11 | + lst[store_index], lst[end] = lst[end], lst[store_index] |
| 12 | + return store_index |
| 13 | + |
| 14 | + |
| 15 | +def quick_sort(lst, start, end): |
| 16 | + if start >= end: |
| 17 | + return lst |
| 18 | + pivot = randrange(start, end + 1) |
| 19 | + new_pivot = partition(lst, start, end, pivot) |
| 20 | + quick_sort(lst, start, new_pivot - 1) |
| 21 | + quick_sort(lst, new_pivot + 1, end) |
| 22 | + |
| 23 | + |
| 24 | +def sort(lst): |
| 25 | + quick_sort(lst, 0, len(lst) - 1) |
| 26 | + return lst |
| 27 | + |
| 28 | +print sort([]) |
| 29 | +print sort([1, 2, 3, 4]) |
| 30 | +print sort([-5, 3, -2, 3, 19, 5]) |
0 commit comments