Open In App

Python Program for Iterative Merge Sort

Last Updated : 28 Aug, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Following is a typical recursive implementation of Merge Sort that uses last element as pivot. Python] 

Python Program for Iterative Merge Sort

The provided Python code demonstrates the recursive implementation of the Merge Sort algorithm. Merge Sort divides an array into smaller subarrays, sorts them, and then merges them back together to achieve a sorted result. The code comprises two main functions: merge to combine two sorted arrays, and mergesort to recursively split and sort an array. The merge function compares elements from the left and right arrays, creating a sorted result array. The mergesort function repeatedly divides the array until its subarrays have one element, then merges them back. The example sorts an array using Merge Sort and prints both the original and sorted arrays, highlighting the recursive nature of the algorithm.

Python




# Recursive Python Program for merge sort
 
def merge(left, right):
    if not len(left) or not len(right):
        return left or right
 
    result = []
    i, j = 0, 0
    while (len(result) < len(left) + len(right)):
        if left[i] < right[j]:
            result.append(left[i])
            i+= 1
        else:
            result.append(right[j])
            j+= 1
        if i == len(left) or j == len(right):
            result.extend(left[i:] or right[j:])
            break
 
    return result
 
def mergesort(list):
    if len(list) < 2:
        return list
 
    middle = len(list)/2
    left = mergesort(list[:middle])
    right = mergesort(list[middle:])
 
    return merge(left, right)
     
seq = [12, 11, 13, 5, 6, 7]
print("Given array is")
print(seq);
print("\n")
print("Sorted array is")
print(mergesort(seq))
 
# Code Contributed by Mohit Gupta_OMG


Output

Given array is
[12, 11, 13, 5, 6, 7]


Sorted array is
[5, 6, 7, 11, 12, 13]

Time Complexity: O(n*log(n))
Auxiliary Space: O(n)

Please refer complete article on Iterative Merge Sort for more details!



Previous Article
Next Article

Similar Reads

C Program for Iterative Merge Sort
Following is a typical recursive implementation of Merge Sort that uses last element as pivot. C/C++ Code /* Recursive C program for merge sort */ #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; /* Function to merge the two haves arr[l..m] and arr[m+1..r] of array arr[] */ void merge(int arr[], int l, int m, int r); /* l is for left index and r
3 min read
Java Program for Iterative Merge Sort
Following is a typical recursive implementation of Merge Sort that uses last element as pivot. Java Code // Recursive Java Program for merge sort import java.util.Arrays; public class GFG { public static void mergeSort(int[] array) { if(array == null) { return; } if(array.length &amp;gt; 1) { int mid = array.length / 2; // Split left part int[] lef
2 min read
Iterative Merge Sort for Linked List
Given a singly linked list of integers, the task is to sort it using iterative merge sort. Recommended: Please solve it on "PRACTICE" first, before moving on to the solution. Merge Sort is often preferred for sorting a linked list. It is discussed here. However, the method discussed above uses Stack for storing recursion calls. This may consume a l
15+ min read
Iterative Merge Sort
Following is a typical recursive implementation of Merge Sort C/C++ Code // Recursive C++ program for merge sort #include&lt;bits/stdc++.h&gt; using namespace std; // Function to merge the two haves // arr[l..m] and arr[m+1..r] of array arr[] void merge(int arr[], int l, int m, int r); // l is for left index and r is // right index of the sub-array
15+ min read
Merge Sort with O(1) extra space merge and O(n log n) time [Unsigned Integers Only]
We have discussed Merge sort. How to modify the algorithm so that merge works in O(1) extra space and algorithm still works in O(n Log n) time. We may assume that the input values are integers only. Examples: Input : 5 4 3 2 1 Output : 1 2 3 4 5 Input : 999 612 589 856 56 945 243 Output : 56 243 589 612 856 945 999Recommended PracticeMerge SortTry
10 min read
Iterative Deepening Search(IDS) or Iterative Deepening Depth First Search(IDDFS)
There are two common ways to traverse a graph, BFS and DFS. Considering a Tree (or Graph) of huge height and width, both BFS and DFS are not very efficient due to following reasons. DFS first traverses nodes going through one adjacent of root, then next adjacent. The problem with this approach is, if there is a node close to root, but not in first
10 min read
Python Program for Iterative Quick Sort
The code consists of two main functions: partition and quickSortIterative, along with a driver code to test the sorting process. The partition function is used for the process of partitioning a given subarray into two parts - elements less than or equal to the chosen pivot (arr[h]) on the left and elements greater on the right. It operates within t
4 min read
Merge Two Binary Trees by doing Node Sum (Recursive and Iterative)
Given two binary trees. We need to merge them into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new value of the merged node. Otherwise, the non-null node will be used as the node of new tree. Example: Input: Tree 1 Tree 2 2 3 / \ / \ 1 4 6 1 / \ \ 5 2 7 Output: Merged tree: 5 / \ 7 5 / \ \ 5 2 7 No
15+ min read
Quick Sort vs Merge Sort
Quick sort is an internal algorithm which is based on divide and conquer strategy. In this: The array of elements is divided into parts repeatedly until it is not possible to divide it further.It is also known as “partition exchange sort”.It uses a key element (pivot) for partitioning the elements.One left partition contains all those elements that
4 min read
Sorting by combining Insertion Sort and Merge Sort algorithms
Insertion sort: The array is virtually split into a sorted and an unsorted part. Values from the unsorted part are picked and placed at the correct position in the sorted part.Advantages: Following are the advantages of insertion sort: If the size of the list to be sorted is small, insertion sort runs fasterInsertion sort takes O(N) time when eleme
2 min read
three90RightbarBannerImg