Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- file1 = open("QuickSort.txt")
- array = []
- for line in file1:
- array.append(int(line))
- file1.close()
- def findMiddle(array):
- if len(array) % 2 == 1:#then it's even
- middle = len(array)/2
- else: middle = len(array)/2 - 1
- three = [array[0],array[middle],array[-1]]
- return sorted(three)[1]
- def quicksort_leftmost(array):
- global Lcomps
- Lcomps += len(array) - 1
- if len(array) <= 1:
- return array
- p = array[0]
- less, greater = [],[]
- for x in array:
- if x < p: less.append(x)
- elif x > p: greater.append(x)
- return quicksort_leftmost(less) + [p] + quicksort_leftmost(greater)
- def quicksort_rightmost(array):
- global Rcomps
- Rcomps += len(array) - 1
- if len(array) <= 1:
- return array
- p = array[-1]
- less, greater = [],[]
- for x in array:
- if x < p: less.append(x)
- elif x > p: greater.append(x)
- return quicksort_rightmost(less) + [p] + quicksort_rightmost(greater)
- def quicksort_median(array):
- global Mcomps
- Mcomps += len(array) - 1
- if len(array) <= 1:
- return array
- p = findMiddle(array)
- less, greater = [],[]
- for x in array:
- if x < p: less.append(x)
- elif x > p: greater.append(x)
- return quicksort_median(less) + [p] + quicksort_median(greater)
- def runtest(numTrials, array1):
- for i in range(numTrials):
- global Lcomps
- global Rcomps
- global Mcomps
- Lcomps = 0
- Rcomps = 0
- Mcomps = 0
- array1 = array1[:]
- array2 = array1[:]
- array3 = array1[:]
- quicksort_leftmost(array1)
- quicksort_rightmost(array2)
- quicksort_median(array3)
- print "part 1 leftmost", Lcomps
- print "part 2 rightmost", Rcomps
- print "part 3 median", Mcomps
- print
- print "running trials..."
- runtest(1,array)
Advertisement
Add Comment
Please, Sign In to add comment