Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Practice Sorting
  • MCQs on Sorting
  • Tutorial on Sorting
  • Bubble Sort
  • Quick Sort
  • Merge Sort
  • Insertion Sort
  • Selection Sort
  • Heap Sort
  • Sorting Complexities
  • Radix Sort
  • ShellSort
  • Counting Sort
  • Bucket Sort
  • TimSort
  • Bitonic Sort
  • Uses of Sorting Algorithm
Open In App
Next Article:
Strand Sort in Python
Next article icon

3-way Merge Sort in Python

Last Updated : 12 Apr, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Merge sort involves recursively splitting the array into 2 parts, sorting, and finally merging them. A variant of merge sort is called 3-way merge sort where instead of splitting the array into 2 parts we split it into 3 parts. 

Examples:

Input: arr = [12, 11, 13, 5, 6, 7]
Output: [5, 6, 7, 11, 12, 13]

Input: arr = [38, 27, 43, 3, 9, 82, 10]
Output: [3, 9, 10, 27, 38, 43, 82]

Approach:

Merge sort recursively breaks down the arrays to subarrays of size half. Similarly, 3-way Merge sort breaks down the arrays to subarrays of size one third. 

Step-by-step algorithm:

  1. Divide the unsorted list into three sublists.
  2. Recursively sort each sublist.
  3. Merge the three sorted sublists to produce the final sorted list.

Below is the implementation of the above idea:

Python3
# Python Program to perform 3 way Merge Sort  """ Merge the sorted ranges [low, mid1), [mid1,mid2)  and [mid2, high) mid1 is first midpoint  index in overall range to merge mid2 is second  midpoint index in overall range to merge"""   def merge(gArray, low, mid1, mid2, high, destArray):     i = low     j = mid1     k = mid2     l = low      # Choose smaller of the smallest in the three ranges     while ((i < mid1) and (j < mid2) and (k < high)):         if(gArray[i] < gArray[j]):             if(gArray[i] < gArray[k]):                 destArray[l] = gArray[i]                 l += 1                 i += 1             else:                 destArray[l] = gArray[k]                 l += 1                 k += 1         else:             if(gArray[j] < gArray[k]):                 destArray[l] = gArray[j]                 l += 1                 j += 1             else:                 destArray[l] = gArray[k]                 l += 1                 k += 1      # Case where first and second ranges     # have remaining values     while ((i < mid1) and (j < mid2)):         if(gArray[i] < gArray[j]):             destArray[l] = gArray[i]             l += 1             i += 1         else:             destArray[l] = gArray[j]             l += 1             j += 1      # case where second and third ranges     # have remaining values     while ((j < mid2) and (k < high)):         if(gArray[j] < gArray[k]):             destArray[l] = gArray[j]             l += 1             j += 1         else:             destArray[l] = gArray[k]             l += 1             k += 1      # Case where first and third ranges have     # remaining values     while ((i < mid1) and (k < high)):         if(gArray[i] < gArray[k]):             destArray[l] = gArray[i]             l += 1             i += 1         else:             destArray[l] = gArray[k]             l += 1             k += 1      # Copy remaining values from the first range     while (i < mid1):         destArray[l] = gArray[i]         l += 1         i += 1      # Copy remaining values from the second range     while (j < mid2):         destArray[l] = gArray[j]         l += 1         j += 1      # Copy remaining values from the third range     while (k < high):         destArray[l] = gArray[k]         l += 1         k += 1   """ Performing the merge sort algorithm on the  given array of values in the rangeof indices  [low, high). low is minimum index, high is  maximum index (exclusive) """   def mergeSort3WayRec(gArray, low, high, destArray):     # If array size is 1 then do nothing     if (high - low < 2):         return      # Splitting array into 3 parts     mid1 = low + ((high - low) // 3)     mid2 = low + 2 * ((high - low) // 3) + 1      # Sorting 3 arrays recursively     mergeSort3WayRec(destArray, low, mid1, gArray)     mergeSort3WayRec(destArray, mid1, mid2, gArray)     mergeSort3WayRec(destArray, mid2, high, gArray)      # Merging the sorted arrays     merge(destArray, low, mid1, mid2, high, gArray)   def mergeSort3Way(gArray, n):     # if array size is zero return null     if (n == 0):         return      # creating duplicate of given array     fArray = []      # copying elements of given array into     # duplicate array     fArray = gArray.copy()      # sort function     mergeSort3WayRec(fArray, 0, n, gArray)      # copy back elements of duplicate array     # to given array     gArray = fArray.copy()      # return the sorted array     return gArray   data = [45, -2, -45, 78, 30, -42, 10, 19, 73, 93] data = mergeSort3Way(data, 10) print("After 3 way merge sort: ", end="") for i in range(10):     print(f"{data[i]} ", end="") 

Output
After 3 way merge sort: -45 -42 -2 10 19 30 45 73 78 93 

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

Advantages of 3-way Merge Sort:

  1. Efficiency: 3-way merge sort can be more efficient than traditional merge sort, especially when dealing with large datasets or arrays with many duplicate elements.
  2. Reduced Number of Comparisons: By merging three sorted sub-arrays instead of two, the number of comparisons needed during merging is reduced, leading to potentially faster sorting.
  3. Improved Performance: In certain scenarios, 3-way merge sort can outperform traditional merge sort, resulting in better overall performance.
  4. Stable Sorting: Like traditional merge sort, 3-way merge sort is stable, meaning it preserves the relative order of equal elements in the sorted array.

Disadvantages of 3-way Merge Sort:

  1. Extra Overhead: Implementing and managing the merging of three sub-arrays instead of two can introduce additional complexity and overhead, potentially impacting performance.
  2. Increased Memory Usage: 3-way merge sort may require more memory compared to traditional merge sort due to the need to merge three sub-arrays instead of two, especially for larger datasets.
  3. Limited Impact: The benefits of 3-way merge sort may not always be significant, particularly for small or already partially sorted arrays, where the overhead of managing three sub-arrays may outweigh any potential performance gains.

Next Article
Strand Sort in Python

S

srinam
Improve
Article Tags :
  • Sorting
  • DSA
  • Python-DSA
Practice Tags :
  • Sorting

Similar Reads

  • 3-way Merge Sort
    Merge Sort is a divide-and-conquer algorithm that recursively splits an array into two halves, sorts each half, and then merges them. A variation of this is 3-way Merge Sort, where instead of splitting the array into two parts, we divide it into three equal parts. In traditional Merge Sort, the arra
    14 min read
  • Strand Sort in Python
    Strand Sort is a sorting algorithm that works by repeatedly pulling out sorted subsequences from the unsorted list and merging them to form a sorted list. It is particularly useful for linked lists due to its efficiency in handling such data structures. Strand Sort Algorithm:Initialize:Start with an
    2 min read
  • Tim Sort in Python
    Tim Sort is a hybrid sorting algorithm derived from merge sort and insertion sort. It is designed to perform well on many kinds of real-world data. Tim Sort's efficiency comes from its ability to exploit the structure present in the data, such as runs (consecutive sequences that are already ordered)
    5 min read
  • Tree Sort in Python
    Tree sort is a sorting algorithm that builds a Binary Search Tree (BST) from the elements of the array to be sorted and then performs an in-order traversal of the BST to get the elements in sorted order. In this article, we will learn about the basics of Tree Sort along with its implementation in Py
    3 min read
  • Sorted merge in one array
    Given two sorted arrays, A and B, where A has a large enough buffer at the end to hold B. Merge B into A in sorted order. Examples: Input : a[] = {10, 12, 13, 14, 18, NA, NA, NA, NA, NA} b[] = {16, 17, 19, 20, 22};; Output : a[] = {10, 12, 13, 14, 16, 17, 18, 19, 20, 22} One way is to merge the two
    7 min read
  • In-Place Merge Sort
    Implement Merge Sort i.e. standard implementation keeping the sorting algorithm as in-place. In-place means it does not occupy extra memory for merge operation as in the standard case. Examples: Input: arr[] = {2, 3, 4, 1} Output: 1 2 3 4 Input: arr[] = {56, 2, 45} Output: 2 45 56 Approach 1: Mainta
    15+ min read
  • In-Place Merge Sort | Set 2
    Given an array A[] of size N, the task is to sort the array in increasing order using In-Place Merge Sort. Examples: Input: A = {5, 6, 3, 2, 1, 6, 7}Output: {1, 2, 3, 5, 6, 6, 7} Input: A = {2, 3, 4, 1}Output: {1, 2, 3, 4} Approach: The idea is to use the inplace_merge() function to merge the sorted
    7 min read
  • Merge two sorted arrays in Python using heapq
    Given two sorted arrays, the task is to merge them in a sorted manner. Examples: Input : arr1 = [1, 3, 4, 5] arr2 = [2, 4, 6, 8] Output : arr3 = [1, 2, 3, 4, 4, 5, 6, 8] Input : arr1 = [5, 8, 9] arr2 = [4, 7, 8] Output : arr3 = [4, 5, 7, 8, 8, 9] This problem has existing solution please refer Merge
    2 min read
  • Merge Sort vs. Insertion Sort
    Pre-requisite: Merge Sort, Insertion Sort Merge Sort: is an external algorithm based on divide and conquer strategy. In this sorting:   The elements are split into two sub-arrays (n/2) again and again until only one element is left.Merge sort uses additional storage for sorting the auxiliary array.M
    14 min read
  • Bucket Sort - Python
    Bucket sort is a sorting technique that involves dividing elements into various groups, or buckets. These buckets are formed by uniformly distributing the elements. Once the elements are divided into buckets, they can be sorted using any other sorting algorithm. Finally, the sorted elements are gath
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences