thinkpad20

algorithms 2 QuickSort progress

Apr 16th, 2012
201
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.90 KB | None | 0 0
  1. file1 = open("QuickSort.txt")
  2. array = []
  3. for line in file1:
  4.     array.append(int(line))
  5. file1.close()
  6.  
  7. def findMiddle(array):
  8.     if len(array) % 2 == 1:#then it's even
  9.         middle = len(array)/2
  10.     else: middle = len(array)/2 - 1
  11.     three = [array[0],array[middle],array[-1]]
  12.     return sorted(three)[1]
  13.  
  14. def quicksort_leftmost(array):
  15.     global Lcomps
  16.     Lcomps += len(array) - 1
  17.     if len(array) <= 1:
  18.         return array
  19.     p = array[0]
  20.     less, greater = [],[]
  21.     for x in array:
  22.         if x < p: less.append(x)
  23.         elif x > p: greater.append(x)
  24.     return quicksort_leftmost(less) + [p] + quicksort_leftmost(greater)
  25.  
  26. def quicksort_rightmost(array):
  27.     global Rcomps
  28.     Rcomps += len(array) - 1
  29.     if len(array) <= 1:
  30.         return array
  31.     p = array[-1]
  32.     less, greater = [],[]
  33.     for x in array:
  34.         if x < p: less.append(x)
  35.         elif x > p: greater.append(x)
  36.     return quicksort_rightmost(less) + [p] + quicksort_rightmost(greater)
  37.  
  38. def quicksort_median(array):
  39.     global Mcomps
  40.     Mcomps += len(array) - 1
  41.     if len(array) <= 1:
  42.         return array
  43.     p = findMiddle(array)
  44.     less, greater = [],[]
  45.     for x in array:
  46.         if x < p: less.append(x)
  47.         elif x > p: greater.append(x)
  48.     return quicksort_median(less) + [p] + quicksort_median(greater)
  49.  
  50. def runtest(numTrials, array1):
  51.     for i in range(numTrials):
  52.         global Lcomps
  53.         global Rcomps
  54.         global Mcomps
  55.  
  56.         Lcomps = 0
  57.         Rcomps = 0
  58.         Mcomps = 0
  59.        
  60.         array1 = array1[:]
  61.         array2 = array1[:]
  62.         array3 = array1[:]
  63.  
  64.         quicksort_leftmost(array1)
  65.         quicksort_rightmost(array2)
  66.         quicksort_median(array3)
  67.  
  68.         print "part 1 leftmost", Lcomps
  69.         print "part 2 rightmost", Rcomps
  70.         print "part 3 median", Mcomps
  71.         print
  72.  
  73. print "running trials..."
  74. runtest(1,array)
Advertisement
Add Comment
Please, Sign In to add comment