thinkpad20

algorithms 1 inversions

Apr 16th, 2012
159
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.25 KB | None | 0 0
  1. file1 = open("IntegerArray.txt")
  2. array = []
  3. count = 0
  4. for line in file1:
  5.     if count == 10:
  6.         break
  7.     array.append(int(line))
  8. file1.close()
  9.  
  10. def mergeSort_count(list1, invCounter):
  11.     if len(list1)<=1:
  12.         return list1, invCounter
  13.     else:
  14.         midPoint = len(list1)/2
  15.         left, invCounterL = mergeSort_count(list1[:midPoint], invCounter)
  16.         right, invCounterR = mergeSort_count(list1[midPoint:], invCounter)
  17.         invCounter = invCounter + invCounterL + invCounterR
  18.     return merge_count(left,right, invCounter)
  19.  
  20. def merge_count(list1, list2, invCounter):
  21.     output = []
  22.     i = 0
  23.     j = 0
  24.     splitInvs = 0
  25.     while i<len(list1) and j < len(list2):
  26.         if list1[i] < list2[j]:
  27.             output.append(list1[i])
  28.             i += 1
  29.         else:
  30.             output.append(list2[j])
  31.             j += 1
  32.             splitInvs += len(list1)-i
  33.     while i<len(list1):
  34.         output.append(list1[i])
  35.         i += 1
  36.     while j<len(list2):
  37.         output.append(list2[j])
  38.         j += 1
  39.     invCounter += splitInvs
  40.     return output, invCounter
  41.  
  42. def mc_wrapper(list1):
  43.     invCounter = 0
  44.     finlist, finalCount = mergeSort_count(list1, invCounter)
  45.     return finalCount
  46.    
  47. print mc_wrapper(array)
Advertisement
Add Comment
Please, Sign In to add comment