
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Explain Merge Sort in Python
Merge sort is a sorting technique. It is an efficient sorting algorithm with a time complexity of (n logn) where n is the length of the array to be sorted.
Merge sort is an algorithm that follows the Divide and Conquers paradigm. It continuously divides the array into two equal halves. Later it starts sorting the lists having a single element each and continuously merges the sorted lists to form the complete sorted list.
Hence, we obtain a sorted array.
Example
The purple boxes and black arrows show the splitting of the list into two halves.
The green boxes and red arrows show the merging of the two sorted lists.
Implement Merge Sort
Splitting the list into two halves is quite easy and it is done recursively until we have only one element left. Later the merging procedure is done which is actually where we apply the logic of merging the two sorted lists together.
Example
The merge function takes the two sorted arrays to be merged. The frontmost element of a1 is compared with the frontmost element of a2. The smallest of two is added to list c and the pointer of that array is incremented.
def merge(a1,a2): c=[] x=0 y=0 while(x<len(a1) and y<len(a2)): if(a1[x]<a2[y]): c.append(a1[x]) x+=1 else: c.append(a2[y]) y+=1 while(x<len(a1)): c.append(a1[x]) x+=1 while(y<len(a2)): c.append(a2[y]) y+=1 return c def mergesort(array): if(len(array)==1): return array mid=(len(array))//2 a1=mergesort(array[:mid]) a2=mergesort(array[mid:]) return merge(a1,a2) array=[2,3,1,5,4,6,8,10,7,9] print(mergesort(array))
Output
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
- Related Articles
- Explain the merge sort technique in C language
- Python Program for Merge Sort
- Python Program for Iterative Merge Sort
- Merge Sort
- Merge sort vs quick sort in Javascript
- Merge Sort Tree in C++
- Python Program to Merge Two Lists and Sort it
- Difference Between Quick Sort and Merge Sort
- Find array with k number of merge sort calls in Python
- 3-way Merge Sort in C++
- Merge Sort using Multithreading in C++
- Program to merge intervals and sort them in ascending order in Python
- How to implement merge sort in JavaScript?
- Using merge sort to recursive sort an array JavaScript
- C++ Program to Implement Merge Sort
