# In this version of Merge sort, instead of creating new lists, # a constant work buffer is needed. import timing # only use on Unix/Linux systems import time import sys from random import * ### mergesort for arrays, with constant work buffer: O(n) extra memory needed. def copypart(M,N,s,e): # copy M[s:e] to same cells in N i = s while i= 2): # else no sorting needed m = (e+s)/2 # midpoint msort(s,m) # recursively sort first partition msort(m,e) # sort second partition merge(s,m,e) # merge sorted partition #msort msort(0,n) # body of mergesort initiates call to msort #mergesort ###### bubblesort (optimized) for comparison def bubblesort(A): n = len(A) i, j = 0,0 while iA[j+1]: A[j],A[j+1] = A[j+1],A[j] # swap j +=1 # while j i +=1 # while i ## bubblesort def sorted(A): # function to check if array is sorted (to verify sorting) ax = True i = 0 while iA[i+1]: ax = False i += 1 return ax ## sorted #A = [4,8,1,3,7,2,5,6] #mergesort(A) #print A if len(sys.argv)>1: size = int(sys.argv[1]) # size of test array as command-line argument else: size = 2000 # default size of random array ## generate random array A=[0]*size i = 0 while i