Quicksort in Python
import random
class QuickSort :
def __init__(self):
self.r = random.Random()
def sort(self, input):
if len(input) <= 1 :
return input
pivot = self.r.randint(0, len(input)-1)
pivotValue = input[pivot]
left = list()
right = list()
s = 0
for elem in input:
s = s + elem
if elem < pivotValue :
left.append(elem)
else :
right.append(elem)
if (len(left)==0 or len(right)==0) \
and s/float(len(input)) == pivotValue:
return input
return self.sort(left) + self.sort(right)
if __name__ == "__main__":
sorter = QuickSort()
print sorter.sort([1,3,2,4,2,5,3,4,3,3,2,32,235,23,523,5,235,23-253])
class QuickSort :
def __init__(self):
self.r = random.Random()
def sort(self, input):
if len(input) <= 1 :
return input
pivot = self.r.randint(0, len(input)-1)
pivotValue = input[pivot]
left = list()
right = list()
s = 0
for elem in input:
s = s + elem
if elem < pivotValue :
left.append(elem)
else :
right.append(elem)
if (len(left)==0 or len(right)==0) \
and s/float(len(input)) == pivotValue:
return input
return self.sort(left) + self.sort(right)
if __name__ == "__main__":
sorter = QuickSort()
print sorter.sort([1,3,2,4,2,5,3,4,3,3,2,32,235,23,523,5,235,23-253])
<< Home