1

I'm trying to implement an algorithm that searches for inversions. I'm having trouble printing the updated global variable c. Where should I put the print statement?

I'd prefer using a method that involves the boilerplate(?) because I'm going to run a timing function to test the running time later. If I could only get it to print the result (8). If I put it inside the merge function(before return C) it returns all the values up to 8. I want it to just print c at the end of the process.

c=0
def merge(A,B):

    global c
    C=[]
    lenA=len(A)
    lenB=len(B)
    i=0
    j=0
    while i<lenA and j<lenB:
        if A[i]<=B[j]:
            C.append(A[i])
            i=i+1
        else:
            c=c+len(A)-i 
            C.append(B[j])
            j=j+1
    if i==lenA:  #A get to the end
        C.extend(B[j:])
    else:
        C.extend(A[i:])
    return C


def inversions_divide_conquer(Array):
    N=len(Array)
    if N>1:
        S1=inversions_divide_conquer(Array[0:N/2])
        S2=inversions_divide_conquer(Array[N/2:])
        return merge(S1,S2)
    else:
        return Array



if __name__ == '__main__':

    inversions_divide_conquer([4, 1, 3, 2, 9, 1])
Veedrac
  • 58,273
  • 15
  • 112
  • 169
user2812970
  • 103
  • 2
  • 10

1 Answers1

0
M = len(stuff)
def inversions_divide_conquer(Array):
    N=len(Array)
    if N>1:
        S1=inversions_divide_conquer(Array[0:N/2])
        S2=inversions_divide_conquer(Array[N/2:])
        if N == M:
            print c
        return merge(S1,S2)
    else:
        return Array

inversions_divide_conquer(stuff)
santosh.ankr
  • 671
  • 4
  • 12
  • does a nested if statement increase running time? I want it to be still O(nlogn). Also could I get an explanation? sorry. I don't quite get what you did. – user2812970 Sep 26 '13 at 04:07
  • Real time, yes, of course, but not too much. Asymptotic run-time, not unless checking the if requires some further computation. In this case, it does not, because you're just comparing two constants. As an aside, what's the problem you're trying to solve? – santosh.ankr Sep 26 '13 at 04:08
  • The problem I was given is to write both the O(N^2) algorithm and the O(nlogn) algorithm. Then test the Running times of both algorithms using the built in timeit feature in Python. I have code for both algorithms but I'm just stuck on the print statement. – user2812970 Sep 26 '13 at 04:11
  • Right, I mean, when you say you're counting inversions, are you trying to count, in an array, the number of pairs x,y such that x>y and x is located before y? – santosh.ankr Sep 26 '13 at 04:14
  • Yes a pair of elements ai and aj represent an inversion if i < j but ai > aj – user2812970 Sep 26 '13 at 04:16