Sunday 18 May 2014

Count Inversions in an array - coursera Programming Question-1 python mearge sort

Data taken from text file code:-

#load the array with text file
fin = open(../../coresera/inversions/IntegerArray.txt)
A=[]
for line in fin:
    A.append(int(line.strip()))

mearge sort : python code

import random
from sys import maxsize as inf


def merge_sort(A):
def merge(L, R):
m = len(L)-1
B = []
i = j = 0
inv = 0
while L[i] != inf or R[j] != inf:
if L[i] <= R[j]:
B.append(L[i])
i += 1
else:
B.append(R[j])
inv += m - i
j += 1
return B, inv
n = len(A)
inv = 0
if n >= 2:
mid = n // 2
L, R = A[:mid], A[mid:]
L, inv_left = merge_sort(L)
R, inv_right = merge_sort(R)
A, inv_split = merge(L + [inf], R + [inf])
inv = inv_left + inv_right + inv_split
return A, inv


if __name__ == '__main__':
A = [1,6,3,2,4,5]
A, inv = merge_sort(A)
print (inv)
print (A)



# Count the number of lines in a file.
if __name__ == "__main__":
    in_file = open("../../coresera/inversions/IntegerArray.txt")
    line_count = 0
    while True:
        in_line = in_file.readline().strip()
        if in_line == "":
            break;
        line_count += 1
    in_file.close()
    print("Line count:", line_count)




2407905288

No comments:

Post a Comment