1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| import random class Random_quick_sort(object): def _randomized_partition(self, alist, p, r): i = random.randint(p, r) alist[i], alist[r] = alist[r], alist[i] return self._partition(alist, p, r) def _partition(self, alist, p, r): i = p-1 x = alist[r] for j in range(p, r): if alist[j]<=x: i += 1 alist[i], alist[j] = alist[j], alist[i] alist[i+1], alist[r] = alist[r], alist[i+1] return i+1 def _quicksort(self, alist, p, r): if p<r: q = self._randomized_partition(alist, p, r) self._quicksort(alist, p, q-1) self._quicksort(alist, q+1, r) def __call__(self, sort_list): self._quicksort(sort_list, 0, len(sort_list)-1) return sort_list if __name__ == "__main__": sort_list = [4,2,7,3,1,9,33,25,46,21,45,22] print sort_list random_quick = Random_quick_sort() print random_quick(sort_list)
|