VOOZH about

URL: https://www.geeksforgeeks.org/dsa/3-way-merge-sort-in-python/

⇱ 3-way Merge Sort in Python - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

3-way Merge Sort in Python

Last Updated : 23 Jul, 2025

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:


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)

  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.
  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.
Comment
Article Tags: