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 array is recursively divided into halves until we reach subarrays of size 1. In 3-way Merge Sort, the array is recursively divided into three parts, reducing the depth of recursion and potentially improving efficiency.
Examples:
Input: arr = [45, -2, -45, 78, 30, -42, 10, 19, 73, 93]
Output: [-45, -42, -2, 10, 19, 30, 45, 73, 78, 93]
Input: arr = [23, -19]
Output: [-19, 23]
Approach:
The idea is to extend merge sort by dividing the array into three parts instead of two. First, recursively sort the three subarrays. Then, merge them by selecting the smallest element among the three at each step. Temporary arrays store the divided parts, and a comparison process finds the minimum to insert into the original array.
Steps to implement the above idea:
- Divide the array into three equal parts using two midpoints.
- Recursively sort each of the three subarrays.
- Create temporary arrays to store the three divided parts.
- Use three pointers to track positions in the three subarrays.
- Find the minimum element among the three at each step.
- Merge the sorted subarrays back into the original array.
- Repeat the process until the entire array is sorted.
C++
// C++ program to implement 3-way Merge Sort
#include <bits/stdc++.h>
using namespace std;
void merge(int arr[], int left, int mid1, int mid2, int right) {
// Sizes of three subarrays
int size1 = mid1 - left + 1;
int size2 = mid2 - mid1;
int size3 = right - mid2;
// Temporary arrays for three parts
vector<int> leftArr(size1), midArr(size2), rightArr(size3);
// Copy data to temporary arrays
for (int i = 0; i < size1; i++) {
leftArr[i] = arr[left + i];
}
for (int i = 0; i < size2; i++) {
midArr[i] = arr[mid1 + 1 + i];
}
for (int i = 0; i < size3; i++) {
rightArr[i] = arr[mid2 + 1 + i];
}
// Merge three sorted subarrays
int i = 0, j = 0, k = 0, index = left;
while (i < size1 || j < size2 || k < size3) {
int minValue = INT_MAX, minIdx = -1;
// Find the smallest among the three current elements
if (i < size1 && leftArr[i] < minValue) {
minValue = leftArr[i];
minIdx = 0;
}
if (j < size2 && midArr[j] < minValue) {
minValue = midArr[j];
minIdx = 1;
}
if (k < size3 && rightArr[k] < minValue) {
minValue = rightArr[k];
minIdx = 2;
}
// Place the smallest element in the merged array
if (minIdx == 0) {
arr[index++] = leftArr[i++];
} else if (minIdx == 1) {
arr[index++] = midArr[j++];
} else {
arr[index++] = rightArr[k++];
}
}
}
void threeWayMergeSort(int arr[], int left, int right) {
// Base case: If single element, return
if (left >= right) {
return;
}
// Finding two midpoints for 3-way split
int mid1 = left + (right - left) / 3;
int mid2 = left + 2 * (right - left) / 3;
// Recursively sort first third
threeWayMergeSort(arr, left, mid1);
// Recursively sort second third
threeWayMergeSort(arr, mid1 + 1, mid2);
// Recursively sort last third
threeWayMergeSort(arr, mid2 + 1, right);
// Merge the sorted parts
merge(arr, left, mid1, mid2, right);
}
int main() {
// Input array
int arr[] = {5, 2, 9, 1, 6, 3, 8, 4, 7};
// Size of the array
int n = sizeof(arr) / sizeof(arr[0]);
// Calling 3-way merge sort function
threeWayMergeSort(arr, 0, n - 1);
// Printing the sorted array
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
return 0;
}
C
// C program to implement 3-way Merge Sort
#include <stdio.h>
#include <limits.h>
#include <stdlib.h>
void merge(int arr[], int left, int mid1, int mid2, int right) {
// Sizes of three subarrays
int size1 = mid1 - left + 1;
int size2 = mid2 - mid1;
int size3 = right - mid2;
// Temporary arrays for three parts
int *leftArr = (int *)malloc(size1 * sizeof(int));
int *midArr = (int *)malloc(size2 * sizeof(int));
int *rightArr = (int *)malloc(size3 * sizeof(int));
// Copy data to temporary arrays
for (int i = 0; i < size1; i++) {
leftArr[i] = arr[left + i];
}
for (int i = 0; i < size2; i++) {
midArr[i] = arr[mid1 + 1 + i];
}
for (int i = 0; i < size3; i++) {
rightArr[i] = arr[mid2 + 1 + i];
}
// Merge three sorted subarrays
int i = 0, j = 0, k = 0, index = left;
while (i < size1 || j < size2 || k < size3) {
int minValue = INT_MAX, minIdx = -1;
// Find the smallest among the three current elements
if (i < size1 && leftArr[i] < minValue) {
minValue = leftArr[i];
minIdx = 0;
}
if (j < size2 && midArr[j] < minValue) {
minValue = midArr[j];
minIdx = 1;
}
if (k < size3 && rightArr[k] < minValue) {
minValue = rightArr[k];
minIdx = 2;
}
// Place the smallest element in the merged array
if (minIdx == 0) {
arr[index++] = leftArr[i++];
} else if (minIdx == 1) {
arr[index++] = midArr[j++];
} else {
arr[index++] = rightArr[k++];
}
}
free(leftArr);
free(midArr);
free(rightArr);
}
void threeWayMergeSort(int arr[], int left, int right) {
// Base case: If single element, return
if (left >= right) {
return;
}
// Finding two midpoints for 3-way split
int mid1 = left + (right - left) / 3;
int mid2 = left + 2 * (right - left) / 3;
// Recursively sort first third
threeWayMergeSort(arr, left, mid1);
// Recursively sort second third
threeWayMergeSort(arr, mid1 + 1, mid2);
// Recursively sort last third
threeWayMergeSort(arr, mid2 + 1, right);
// Merge the sorted parts
merge(arr, left, mid1, mid2, right);
}
int main() {
// Input array
int arr[] = {5, 2, 9, 1, 6, 3, 8, 4, 7};
// Size of the array
int n = sizeof(arr) / sizeof(arr[0]);
// Calling 3-way merge sort function
threeWayMergeSort(arr, 0, n - 1);
// Printing the sorted array
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
return 0;
}
Java
// Java program to implement 3-way Merge Sort
import java.util.*;
class GfG {
static void merge(int arr[], int left, int mid1, int mid2, int right) {
// Sizes of three subarrays
int size1 = mid1 - left + 1;
int size2 = mid2 - mid1;
int size3 = right - mid2;
// Temporary arrays for three parts
int[] leftArr = new int[size1];
int[] midArr = new int[size2];
int[] rightArr = new int[size3];
// Copy data to temporary arrays
for (int i = 0; i < size1; i++) {
leftArr[i] = arr[left + i];
}
for (int i = 0; i < size2; i++) {
midArr[i] = arr[mid1 + 1 + i];
}
for (int i = 0; i < size3; i++) {
rightArr[i] = arr[mid2 + 1 + i];
}
// Merge three sorted subarrays
int i = 0, j = 0, k = 0, index = left;
while (i < size1 || j < size2 || k < size3) {
int minValue = Integer.MAX_VALUE, minIdx = -1;
// Find the smallest among the three current elements
if (i < size1 && leftArr[i] < minValue) {
minValue = leftArr[i];
minIdx = 0;
}
if (j < size2 && midArr[j] < minValue) {
minValue = midArr[j];
minIdx = 1;
}
if (k < size3 && rightArr[k] < minValue) {
minValue = rightArr[k];
minIdx = 2;
}
// Place the smallest element in the merged array
if (minIdx == 0) {
arr[index++] = leftArr[i++];
} else if (minIdx == 1) {
arr[index++] = midArr[j++];
} else {
arr[index++] = rightArr[k++];
}
}
}
static void threeWayMergeSort(int arr[], int left, int right) {
// Base case: If single element, return
if (left >= right) {
return;
}
// Finding two midpoints for 3-way split
int mid1 = left + (right - left) / 3;
int mid2 = left + 2 * (right - left) / 3;
// Recursively sort first third
threeWayMergeSort(arr, left, mid1);
// Recursively sort second third
threeWayMergeSort(arr, mid1 + 1, mid2);
// Recursively sort last third
threeWayMergeSort(arr, mid2 + 1, right);
// Merge the sorted parts
merge(arr, left, mid1, mid2, right);
}
public static void main(String args[]) {
// Input array
int arr[] = {5, 2, 9, 1, 6, 3, 8, 4, 7};
// Size of the array
int n = arr.length;
// Calling 3-way merge sort function
threeWayMergeSort(arr, 0, n - 1);
// Printing the sorted array
for (int i = 0; i < n; i++) {
System.out.print(arr[i] + " ");
}
}
}
Python
# Python program to implement 3-way Merge Sort
def merge(arr, left, mid1, mid2, right):
# Sizes of three subarrays
size1 = mid1 - left + 1
size2 = mid2 - mid1
size3 = right - mid2
# Temporary arrays for three parts
left_arr = arr[left:left + size1]
mid_arr = arr[mid1 + 1:mid1 + 1 + size2]
right_arr = arr[mid2 + 1:mid2 + 1 + size3]
# Merge three sorted subarrays
i = j = k = 0
index = left
while i < size1 or j < size2 or k < size3:
min_value = float('inf')
min_idx = -1
# Find the smallest among the three current elements
if i < size1 and left_arr[i] < min_value:
min_value = left_arr[i]
min_idx = 0
if j < size2 and mid_arr[j] < min_value:
min_value = mid_arr[j]
min_idx = 1
if k < size3 and right_arr[k] < min_value:
min_value = right_arr[k]
min_idx = 2
# Place the smallest element in the merged array
if min_idx == 0:
arr[index] = left_arr[i]
i += 1
elif min_idx == 1:
arr[index] = mid_arr[j]
j += 1
else:
arr[index] = right_arr[k]
k += 1
index += 1
def three_way_merge_sort(arr, left, right):
# Base case: If single element, return
if left >= right:
return
# Finding two midpoints for 3-way split
mid1 = left + (right - left) // 3
mid2 = left + 2 * (right - left) // 3
# Recursively sort first third
three_way_merge_sort(arr, left, mid1)
# Recursively sort second third
three_way_merge_sort(arr, mid1 + 1, mid2)
# Recursively sort last third
three_way_merge_sort(arr, mid2 + 1, right)
# Merge the sorted parts
merge(arr, left, mid1, mid2, right)
if __name__ == "__main__":
# Input array
arr = [5, 2, 9, 1, 6, 3, 8, 4, 7]
# Calling 3-way merge sort function
three_way_merge_sort(arr, 0, len(arr) - 1)
# Printing the sorted array
print(*arr)
C#
// C# program to implement 3-way Merge Sort
using System;
class GfG {
// Function to merge three sorted subarrays
static void Merge(int[] arr, int left, int mid1, int mid2, int right) {
// Sizes of three subarrays
int size1 = mid1 - left + 1;
int size2 = mid2 - mid1;
int size3 = right - mid2;
// Temporary arrays for three parts
int[] leftArr = new int[size1];
int[] midArr = new int[size2];
int[] rightArr = new int[size3];
// Copy data to temporary arrays
for (int i = 0; i < size1; i++) {
leftArr[i] = arr[left + i];
}
for (int i = 0; i < size2; i++) {
midArr[i] = arr[mid1 + 1 + i];
}
for (int i = 0; i < size3; i++) {
rightArr[i] = arr[mid2 + 1 + i];
}
// Merge three sorted subarrays
int i1 = 0, i2 = 0, i3 = 0, index = left;
while (i1 < size1 || i2 < size2 || i3 < size3) {
int minValue = int.MaxValue, minIdx = -1;
// Find the smallest among the three current elements
if (i1 < size1 && leftArr[i1] < minValue) {
minValue = leftArr[i1];
minIdx = 0;
}
if (i2 < size2 && midArr[i2] < minValue) {
minValue = midArr[i2];
minIdx = 1;
}
if (i3 < size3 && rightArr[i3] < minValue) {
minValue = rightArr[i3];
minIdx = 2;
}
// Place the smallest element in the merged array
if (minIdx == 0) {
arr[index++] = leftArr[i1++];
} else if (minIdx == 1) {
arr[index++] = midArr[i2++];
} else {
arr[index++] = rightArr[i3++];
}
}
}
// Function to perform 3-way merge sort
static void ThreeWayMergeSort(int[] arr, int left, int right) {
// Base case: If single element, return
if (left >= right) {
return;
}
// Finding two midpoints for 3-way split
int mid1 = left + (right - left) / 3;
int mid2 = left + 2 * (right - left) / 3;
// Recursively sort first third
ThreeWayMergeSort(arr, left, mid1);
// Recursively sort second third
ThreeWayMergeSort(arr, mid1 + 1, mid2);
// Recursively sort last third
ThreeWayMergeSort(arr, mid2 + 1, right);
// Merge the sorted parts
Merge(arr, left, mid1, mid2, right);
}
// Driver method
public static void Main() {
// Input array
int[] arr = {5, 2, 9, 1, 6, 3, 8, 4, 7};
// Size of the array
int n = arr.Length;
// Calling 3-way merge sort function
ThreeWayMergeSort(arr, 0, n - 1);
// Printing the sorted array
foreach (int num in arr) {
Console.Write(num + " ");
}
}
}
JavaScript
// Javascript program to implement 3-way Merge Sort
function merge(arr, left, mid1, mid2, right) {
// Sizes of three subarrays
let size1 = mid1 - left + 1;
let size2 = mid2 - mid1;
let size3 = right - mid2;
// Temporary arrays for three parts
let leftArr = arr.slice(left, left + size1);
let midArr = arr.slice(mid1 + 1, mid1 + 1 + size2);
let rightArr = arr.slice(mid2 + 1, mid2 + 1 + size3);
// Merge three sorted subarrays
let i = 0, j = 0, k = 0, index = left;
while (i < size1 || j < size2 || k < size3) {
let minValue = Infinity;
let minIdx = -1;
// Find the smallest among the three current elements
if (i < size1 && leftArr[i] < minValue) {
minValue = leftArr[i];
minIdx = 0;
}
if (j < size2 && midArr[j] < minValue) {
minValue = midArr[j];
minIdx = 1;
}
if (k < size3 && rightArr[k] < minValue) {
minValue = rightArr[k];
minIdx = 2;
}
// Place the smallest element in the merged array
if (minIdx === 0) {
arr[index] = leftArr[i++];
} else if (minIdx === 1) {
arr[index] = midArr[j++];
} else {
arr[index] = rightArr[k++];
}
index++;
}
}
function threeWayMergeSort(arr, left, right) {
// Base case: If single element, return
if (left >= right) {
return;
}
// Finding two midpoints for 3-way split
let mid1 = left + Math.floor((right - left) / 3);
let mid2 = left + 2 * Math.floor((right - left) / 3);
// Recursively sort first third
threeWayMergeSort(arr, left, mid1);
// Recursively sort second third
threeWayMergeSort(arr, mid1 + 1, mid2);
// Recursively sort last third
threeWayMergeSort(arr, mid2 + 1, right);
// Merge the sorted parts
merge(arr, left, mid1, mid2, right);
}
// Input array
let arr = [5, 2, 9, 1, 6, 3, 8, 4, 7];
// Calling 3-way merge sort function
threeWayMergeSort(arr, 0, arr.length - 1);
// Printing the sorted array
console.log(...arr);
Time Complexity: O(n log₃ n), because the array is divided into three parts at each level, and merging takes O(n) time per level, leading to a recurrence of T(n) = 3T(n/3) + O(n).
Auxiliary Space: O(n) due to the use of temporary arrays for storing the three subarrays during merging.
Similar article: 3 way Quick Sort
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem