Answers for "Itterative merge sort python"

11

Merge Sort python

def merge_sort(arr):
    # The last array split
    if len(arr) <= 1:
        return arr
    mid = len(arr) // 2
    # Perform merge_sort recursively on both halves
    left, right = merge_sort(arr[:mid]), merge_sort(arr[mid:])

    # Merge each side together
    return merge(left, right, arr.copy())


def merge(left, right, merged):

    left_cursor, right_cursor = 0, 0
    while left_cursor < len(left) and right_cursor < len(right):
      
        # Sort each one and place into the result
        if left[left_cursor] <= right[right_cursor]:
            merged[left_cursor+right_cursor]=left[left_cursor]
            left_cursor += 1
        else:
            merged[left_cursor + right_cursor] = right[right_cursor]
            right_cursor += 1
            
    for left_cursor in range(left_cursor, len(left)):
        merged[left_cursor + right_cursor] = left[left_cursor]
        
    for right_cursor in range(right_cursor, len(right)):
        merged[left_cursor + right_cursor] = right[right_cursor]

    return merged
Posted by: Guest on January-07-2020
1

Merge Sort Python

def mergeSort(arr):

    if len(arr) > 1:

        a = len(arr)//2

        l = arr[:a]

        r = arr[a:]

        # Sort the two halves

        mergeSort(l)

        mergeSort(r) 

        b = c = d = 0

        while b < len(l) and c < len(r):

            if l[b] < r[c]:

                arr[d] = l[b]

                b += 1

            else:

                arr[d] = r[c]

                c += 1

            d += 1

        while b < len(l):

            arr[d] = l[b]

            b += 1

            d += 1

        while c < len(r):

            arr[d] = r[c]

            c += 1

            d += 1


def printList(arr):

    for i in range(len(arr)):

        print(arr[i], end=" ")

    print()
 

# Driver program

if __name__ == '__main__':

    arr = [0,1,3,5,7,9,2,4,6,8] 

    mergeSort(arr) 

    print("Sorted array is: ")

    printList(arr)

 
Posted by: Guest on August-12-2021

Python Answers by Framework

Browse Popular Code Answers by Language