简体   繁体   中英

Inversions count using Merge sort

I am trying to implement the famous : Counting inversions using merge sort. I wrote the code for the same. The code works well for small data. I had a few test cases using which I verified the answer. But the code takes an awful long time when the input is large (100000). So, I just want to make sure that the complexity of my code is O(N lgN) and not higher (being of higher complexity, it might be taking longer time). Here is my code in Python:

    def merge_sort(u_list,inv):
    if(len(u_list) == 1): return 0
    if(len(u_list)>1):
        mid=len(u_list)//2
        l_list=u_list[:mid]
        r_list=u_list[mid:]
        a=merge_sort(l_list,inv)
        b=merge_sort(r_list,inv)
        count=0

        i=0
        j=0
        k=0
        track=0
        while i<len(l_list) and j<len(r_list) :
            if l_list[i]<=r_list[j]:
                u_list[k]=l_list[i]
                track+=1
                i+=1
                k+=1

            else: #r_list[j]<l_list[i]
                u_list[k]=r_list[j]
                inv=inv+(len(l_list)-track)
                j+=1
                k+=1

        while i<len(l_list) :
            u_list[k]=l_list[i]
            i+=1
            k+=1

        while j<len(r_list):
            u_list[k]=r_list[j]
            j+=1
            k+=1
        count=inv+a+b
        return count

inv=0
m=0
u_list=[]
x=0
for m in range(0,100000):
    x=int(input())
    u_list.append(x)

foo = merge_sort(u_list,inv)
print(foo)

I replaced

for m in range(0,100000):
    x=int(input())
    u_list.append(x)

with

from random import *
u_list = list(range(100000))
shuffle(u_list)

and ran the code and it took about a second, which seems normal. I think your merge sort is fine and something is going wrong on input. How are you passing input to the script? If you are streaming in some big text file is it possible the file isn't 100000 lines and the program just waits forever?

Since I was having the input data in a text file, I replaced :

x=0
for m in range(0,100000):
    x=int(input())
    u_list.append(x)

with this:

fileName = 'IntegerArray.txt'
u_list = []
with open(fileName) as f:
    for line in f:
        u_list.append(int(line))

And got the output in a second or so.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM