简体   繁体   中英

Merge sort for python

Here are my merge and mergeSort functions. merge merges two separate arrays and mergesSort sorts and merges them with recursion:

def merge(arrL, arrR):
    arrNew = []
    d = len(arrL) + len(arrR)
    i = 0
    j = 0
    for k in range (0, d-1):
        if (arrL[i] < arrR[j]) :
            arrNew.append(arrL[i]) # appends to the end of the array
            i = i + 1
        else:
            arrNew.append(arrR[j])
            j = j + 1
    return arrNew

def mergeSort(arr, m, n):
    if (n - m == 1):
        return arr[m]
    else:
        p = (m + n) // 2
        arrL = mergeSort(arr, m, p)
        arrR = mergeSort(arr, p, n)
        arrNew = merge(arrL, arrR)
        return arrNew

I am getting an error from lines 32, 33 and 13:

d = len(arrL) + len(arrR)
TypeError: object of type 'int' has no len()

What is causing this error? merge is taking two arrays as inputs.

What is causing this error? merge is taking two arrays as inputs.

Except when it doesn't.

if(n-m == 1):
  return arr[m]

This output of mergeSort is not an array.

My guess is it's this line

if(n-m == 1):
    return arr[m]

which presumably is returning the content arr[m] of the array and not an array itself.

Since your code sorts arrays, when this naked element gets recursed on, it will generate the error you're seeing.

There are multiple problems in the code:

  • in mergeSort , you should return arr instead of arr[m] when the length of the array is less than 2. The test if (n - m == 1) does not allow for empty arrays:

     if (n - m < 2): return arr
  • in merge , the main loop should run d times, ie: instead of for k in range (0, d-1): you should write:

     for k in range (d):
  • the test in the merge loop should also check if the index value in still in range. If the second slice is exhausted, the element arrL[i] should be selected:

     for k in range (d): if i < len(arrL) and (j >= len(arrR) or arrL[i] < arrR[j]): arrNew.append(arrL[i]) i = i + 1 else: arrNew.append(arrR[j]) j = j + 1

Here is a modified version:

def merge(arrL, arrR):
    arrNew = []
    i = 0
    j = 0
    for k in range(len(arrL) + len(arrR)):
        if i < len(arrL) and (j >= len(arrR) or arrL[i] < arrR[j]):
            arrNew.append(arrL[i])
            i = i + 1
        else:
            arrNew.append(arrR[j])
            j = j + 1
    return arrNew

def mergeSort(arr, m, n):
    if (n - m < 2):
        return arr
    else:
        p = (m + n) // 2
        arrL = mergeSort(arr, m, p)
        arrR = mergeSort(arr, p, n)
        return merge(arrL, arrR)

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