Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
448 views
in Technique[技术] by (71.8m points)

python - Python:在打印合并排序功能的结果时,print选项提供所有步骤。 如何只打印最终排序的数组?(Python: While printing the result of merge sort function, print option gives all steps. How to print only final sorted array?)

Here is the code for the function which must return new sorted list, how do I get only the final arr printed, since it prints all steps?

(这是该函数的代码,该函数必须返回新的排序列表,我如何只打印最终的arr,因为它会打印所有步骤?)

def mergeSort(list_to_sort, ascend=True): arr=list_to_sort

(def mergeSort(list_to_sort,ascend = True):arr = list_to_sort)

if len(arr) > 1:
    mid = len(arr) // 2
    left = arr[:mid]
    right = arr[mid:]

    # Recursive call on each half
    mergeSort(left)
    mergeSort(right)

    # Two iterators for traversing the two halves
    i = 0
    j = 0

    # Iterator for the main list
    k = 0

    while i < len(left) and j < len(right):
        if left[i] < right[j]:
            # The value from the left half has been used
            arr[k] = left[i]
            # Move the iterator forward
            i += 1
        else:
            arr[k] = right[j]
            j += 1
        # Move to the next slot
        k += 1

    # For all the remaining values
    while i < len(left):
        arr[k] = left[i]
        i += 1
        k += 1

    while j < len(right):
        arr[k] = right[j]
        j += 1
        k += 1

    if ascend:
        pass
    else:
        arr = arr[::-1]

print(arr)

mergeSort([54, 26, 93, 17, 77, 31, 44, 55, 20],False)

(mergeSort([54,26,93,17,77,31,44,55,20],假))

  ask by Elizabet Vollerner translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...