thinkpad20

Untitled

Apr 22nd, 2012
160
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.04 KB | None | 0 0
  1. def swap(A,i,j):
  2.     temp = A[i]
  3.     A[i] = A[j]
  4.     A[j] = temp
  5.  
  6. CompCount = [0,0,0]
  7.  
  8. def partitionRight(A, left, right):
  9.     p = A[right]
  10.     i = left
  11.     for j in range(left,right):
  12.         CompCount[1] += 1
  13.         if A[j] < p:
  14.             swap(A,i,j)
  15.             i += 1
  16.     swap(A,right,i)
  17.     return i
  18.  
  19. def partitionLeft(A, left, right):
  20.     p = A[left]
  21.     i = left + 1
  22.     for j in range(left+1,right):
  23.         CompCount[0] += 1
  24.         if A[j] < p:
  25.             swap(A,i,j)
  26.             i += 1
  27.     swap(A,left,i-1)
  28.     return i-1
  29.  
  30. ##def partitionRight(A, left, right):
  31. ##    p = A[right]
  32. ##    i = right-1
  33. ##    for j in range(right-1, left-1, -1):
  34. ##        CompCount[1] += 1
  35. ##        if A[j] > p:
  36. ##            swap(A,i,j)
  37. ##            i -= 1
  38. ##    swap(A,right,i+1)
  39. ##    return i+1
  40.  
  41. def quickSortL(array, left, right):
  42.     if left < right:
  43.         i = partitionLeft(array, left, right)
  44.         quickSortL(array, left, i)
  45.         quickSortL(array, i+1, right)
  46.  
  47. def quickSortR(array, left, right):
  48.     if left < right:
  49.         i = partitionRight(array, left, right)
  50.         print "recursing on left array from",left,"to",i-1
  51.         quickSortR(array, left, i-1)
  52.         print "recursing on right array from",i+1,"to",right
  53.         quickSortR(array, i+1, right)
  54.  
  55. def tester(filename):
  56.     CompCount[0] = 0
  57.     file1 = open(filename)
  58.     testlist2 = []
  59.     for line in file1:
  60.         testlist2.append(int(line))
  61.     file1.close()
  62.     print "initial:"
  63.     print testlist2
  64.     print
  65.     copy1 = testlist2[:]
  66.     copy2 = testlist2[:]
  67.     print "_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-"
  68.     quickSortL(copy1, 0, len(copy1))
  69.     print copy1
  70.     quickSortR(copy2, 0, len(copy2)-1)
  71.     print copy2
  72.     if copy1 == copy2: print "sort results match."
  73.     else: print "sort results don't match."
  74.     print
  75.     print "First element as pivot : %d comparisons" % CompCount[0]
  76.     print "Final element as pivot : %d comparisons" % CompCount[1]
  77.     print "_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-"
  78.     print
  79.  
  80. tester("TestCase2.txt")
Advertisement
Add Comment
Please, Sign In to add comment