Python Nonrecursive Merge Alignment

Asked 2 years ago, Updated 2 years ago, 53 views

def seq_merge_sort(arr):
    rght = 0; wid = 0; rend = 0; left = 0
    k = 1

    num = len(arr)
    temp = [0] * num

    while(k < num):
        while(left + k < num):
            rght = left + k
            rend = rght + k
            if(rend > num):
                rend = num
            m = left; i = left; j = rght

            while(i < rght and j < rend):
                if (arr[i] <= arr[j]):
                    temp[m] = arr[i]
                    i += 1
                else:
                    temp[m] = arr[j]
                    j += 1
                m += 1

            while(i < rght):
                temp[m] = arr[i]
                i += 1; m += 1
            while(j < rend):
                temp[m] = arr[j]
                j += 1; m += 1
            m = left
            while(m < rend):
                arr[m] = temp[m]
                m += 1
            left += k * 2
        k *= 2
    return arr

Non-recursive merge alignment created using Python.

But it's either case by case or not.

There are times when the alignment is complete and times when it is finished.

I sincerely ask for your help from masters who can fix it.

python merge-sort

2022-09-22 14:36

1 Answers

while(k < num): There is no part inside the loop that initializes the left variable. Try changing it like this.

...
    while(k < num):
        left = 0
        while(left + k < num):
...


2022-09-22 14:36

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.