Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8605373
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 12, 20262026-06-12T02:48:52+00:00 2026-06-12T02:48:52+00:00

def merge (seq, p, q, r): # n1: length of sub-array [p..q] n1 =

  • 0
def merge (seq, p, q, r):
    # n1: length of sub-array [p..q]
    n1 = q - p + 1
    # n2: length of sub-array [q+1 ..r]
    n2 = r - q
    # Left and Right arrays
    left_arr = [] 
    right_arr = []
    for i in xrange(0, n1):
        left_arr.append( seq[p+i] )
    for j in xrange(0, n2):
        right_arr.append( seq[q+j+1] )

    j=0
    i=0
    for k in xrange(p,r+1):
        if left_arr[i]<= right_arr[j]:
            seq[k]=left_arr[i]
            i+=1
        else:
            seq[k]=right_arr[j]
            j+=1
    return seq

s = [2,4,5,7,1,2,3,6]
p = 0
q = 3
r = 7
print merge(s,p,q,r)

How it works:

  1. A unsorted sequence s is taken, along with the index numbers where the sequence has to be merged. (p=initial, r = final, q=middle)

  2. Now, left_arr and right_arr are [p,q], [q+1, r] respectively

  3. we take left_arr and right_arr initial values (i=0, j=0). We iterate over the sequence seq…

  4. while iterating we are replacing the values of seq with the sorted values…

The above function is able to sort till last number “7”.. at the end, its showing “IndexError”. I can use exception handling to catch it and fix but I think… for merge sort, its too much.. Can anyone help me in fixing the code as easy as possible.

I am learning Algorithms.. (following book: Introduction to Algorithms by Thomas H. Cormen)

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-12T02:48:54+00:00Added an answer on June 12, 2026 at 2:48 am

    the problem is that at the last iteration i will be equal to 4 and you are trying to access left_arr[5] which does not exist. you should add a stopping condition when i or j become larger then the size of the corresponding array, and then add all the remaining elements in the other array to seq.

    Here is a code that works:

    def merge (seq, p, q, r):
        # n1: length of sub-array [p..q]
        n1 = q - p + 1
        # n2: length of sub-array [q+1 ..r]
        n2 = r - q
        # Left and Right arrays
        left_arr = seq[p:n1] #here 
        right_arr = seq[n1:r+1]  #here
        j=0
        i=0
        for k in xrange(p, r+1):
            if left_arr[i]<= right_arr[j]:
                seq[k]=left_arr[i]
                i+=1
                if i > n1-1: #here
                    break
            else:
                seq[k]=right_arr[j] #here
                j+=1
                if j > n2-1:
                    break
        if i >= len(left_arr): #from here down
            seq[k+1:] = right_arr[j:]
        elif j >= len(right_arr):
            seq[k+1:] = left_arr[i:]
    
        return seq
    
    s = [2,4,5,7,1,1,1,1]
    p = 0
    q = 3
    r = 7
    print merge(s,p,q,r)
    

    I have marked with comments the places where I have edited your code.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I found this code online: def merge(left, right): result = [] i ,j =
def download_if_dne(href, filename): if os.path.isfile(filename): # print 'already downloaded:', href return False else: if
>>> def merge(l1,l2): top1=0 top2=0 while l1[top1]!=None or l2[top2]!=None: if l1[top1]>l2[top2]: l.append(11[top1]) top1=top1+1 print
Here's my python implementation of merge sort: def sort(lst): if len(lst) < 2: return
Here is my code. @@inversions = 0 numbers = [very big array] def merge_sort(array)
def partial(template, *args) options = args.extract_options! options.merge!(:layout => false) if collection = options.delete(:collection) then
def update @album = Album.find(params[:id]) if @album.update_attributes(params[:album]) redirect_to(:action=>'list') else render(:action=>'edit') end end A Rails
def self.get(server) return unless server server = server.to_s if klass = @handlers[server] obj =
def any? if block_given? method_missing(:any?) { |*block_args| yield(*block_args) } else !empty? end end In
def merge(l1,l2): i=0; while((l1[i]!=none)||(l2[i]!=none)): SyntaxError: invalid syntax being a newbie i can't figure out

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.