Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/324.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用合并排序原则_Python_Algorithm_Mergesort - Fatal编程技术网

Python 使用合并排序原则

Python 使用合并排序原则,python,algorithm,mergesort,Python,Algorithm,Mergesort,Q-我有一个苹果大小的数组A,并且必须创建另一个数组S,该数组S将按照排序顺序包含苹果的索引,因为我们不能直接访问或触摸A,只有一个函数是大的(A,I,j)函数才能访问它。它返回-1是A[i]>A[j],如果A[i]苹果大小[j]: 返回1 elif苹果大小[i]

Q-我有一个苹果大小的数组A,并且必须创建另一个数组S,该数组S将按照排序顺序包含苹果的索引,因为我们不能直接访问或触摸A,只有一个函数是大的(A,I,j)函数才能访问它。它返回-1是A[i]>A[j],如果A[i]
def is_large_apples(apple_size, i, j):
    """ Takes two indices and tells
    which one of them is larger or smaller """

    if apple_size[i] > apple_size[j]:
        return 1
    elif apple_size[i] < apple_size[j]:
        return -1

def mergesort_apples(s, l, r):
    """ This function takes indexed list and
     makes recursive calls to sort the array """
    if l < r:
        mid = (l+r)//2
        mergesort_apples(s, l, mid)
        mergesort_apples(s, mid+1, r)
        merge_apples(s, l, mid, r)


def merge_apples(s, l, mid, r):
    """ This function takes the list and
    the indices to merge them into the final array"""
    nl = mid - l + 1
    nr = r - mid
    left, right = [], []
    left = s[l:mid+1:1]
    right = s[mid+1:r+1:1]
    i, j, k = 0, 0, l;
    while i < nl and j < nr:
        print(s)
        if is_large_apples(apple_size, i, j) == -1:
            s[k] = left[i]
            i += 1
        else:
            s[k] = right[j]
            j += 1
        k += 1

    while i < nl:
        s[k] = left[i]
        k += 1
        i += 1
    while j < nr:
        s[k] = right[j]
        k += 1
        j += 1

apple_size = [5, 7, 1,44,2,33] # Given list of sizes.
s = [x for x in range(0,len(apple_size))] # Original list of indices.
mergesort_apples(s, 0, len(s)-1)
print(s)
def是大苹果(苹果大小,i,j):
“”获取两个索引并告诉
哪一个更大或更小
如果苹果大小[i]>苹果大小[j]:
返回1
elif苹果大小[i]<苹果大小[j]:
返回-1
苹果(s,l,r):
“”“此函数接受索引列表和
进行递归调用以对数组“”进行排序
如果l

因为您想检查的不是
i
j
位置,而是
left[i]
位置和
right[j]
位置。

您写道:“结果不正确”-请描述不正确和不正确的结果。把它们包括在你的问题中。请阅读以获取灵感您的列表
s
是[0,1,2],已经是有序的。您不想对
apple\u size
进行排序吗?我想使用is\u large()函数间接对apple\u size进行排序,S应该包含排序大小的索引。另外,如果apple\u size[I]为
if is_large_apples(apple_size, left[i], right[j]) == -1: