Please note, this is a STATIC archive of website www.simplilearn.com from 27 Mar 2023, cach3.com does not collect or store any user information, there is no "phishing" involved.
Everything You Need to Know About the Merge Sort Algorithm

The “Merge Sort”  uses a recursive algorithm to achieve its results. The divide-and-conquer algorithm breaks down a big problem into smaller, more manageable pieces that look similar to the initial problem. It then solves these subproblems recursively and puts their solutions together to solve the original problem.

By the end of this tutorial, you will have a better understanding of the technical fundamentals of the “Merge Sort” with all the necessary details, along with practical examples.

Learn from the Best in the Industry!

Caltech PGP Full Stack DevelopmentExplore Program
Learn from the Best in the Industry!

What Is a Divide and Conquer Algorithm?

merge_sort-divide-and-conquer-img1

Divide-and-conquer recursively solves subproblems; each subproblem must be smaller than the original problem, and each must have a base case. A divide-and-conquer algorithm has three parts:

  • Divide up the problem into a lot of smaller pieces of the same problem.
  • Conquer the subproblems by recursively solving them. Solve the subproblems as base cases if they're small enough.
  • To find the solutions to the original problem, combine the solutions of the subproblems.

What Is a Merge Sort Algorithm?

merge_sort-what-img1.

Merge sort is one of the most efficient sorting algorithms. It is based on the divide-and-conquer strategy. Merge sort continuously cuts down a list into multiple sublists until each has only one item, then merges those sublists into a sorted list.

Get All Your Questions Answered Here!

Caltech PGP Full Stack DevelopmentExplore Program
Get All Your Questions Answered Here!

How Does the Merge Sort Algorithm Work?

Merge sort algorithm can be executed in two ways:

  • Top-down Approach

merge_sort-top-down-img1.

It starts at the top and works its way down, splitting the array in half, making a recursive call, and merging the results until it reaches the bottom of the array tree.

  • Bottom-Up Approach 

merge_sort-bottom-up-img1.

The iterative technique is used in the Bottom-Up merge sort approach. It starts with a "single-element" array and then merges two nearby items while also sorting them. The combined-sorted arrays are merged and sorted again until only one single unit of the sorted array remains.

You have now explored two approaches to execute merge sort. Now, you will learn to implement one of the approaches in a code editor.

Basics to Advanced - Learn It All!

Caltech PGP Full Stack DevelopmentExplore Program
Basics to Advanced - Learn It All!

How to Implement the Merge Sort Algorithm?

It splits the input array in half, calls itself for each half, and then combines the two sorted parts. Merging two halves is done with the merge() method. Merge (array[], left, mid, right) is a crucial process that assumes array[left..mid] and array[mid+1..right]  are both sorted sub-arrays and merges them into one.

Code:

// A C++ program to Sort an array using merge sort algorithm

#include <bits/stdc++.h>

using namespace std;

// Merges two subarrays of array[].

// First subarray is arr[begin..mid]

// Second subarray is arr[mid+1..end]

void merge(int array[], int const left, int const mid, int const right)

{

int const subarrayone = mid - left + 1;

int const subarraytwo = right - mid;

// Create temp arrays

int *leftarray = new int[subarrayone],

*rightarray = new int[subarraytwo];

// Copy data to temp arrays leftarray[] and rightarray[]

for (int i = 0; i < subarrayone; i++)

leftarray[i] = array[left + i];

for (int j = 0; j < subarraytwo; j++)

rightarray[j] = array[mid + 1 + j];

int indexofsubarrayone = 0, // Initial index of first sub-array

indexofsubarraytwo = 0; // Initial index of second sub-array

int indexofmergedarray = left; // Initial index of merged array

// Merge the temp arrays back into array[left..right]

while (indexofsubarrayone < subarrayone && indexofsubarraytwo < subarraytwo) {

if (leftarray[indexofsubarrayone] <= rightarray[indexofsubarraytwo]) {

array[indexofmergedarray] = leftarray[indexofsubarrayone];

indexofsubarrayone++;

}

else {

array[indexofmergedarray] = rightarray[indexofsubarraytwo];

indexofsubarraytwo++;

}

indexofmergedarray++;

}

// Copy the remaining elements of

// left[], if there are any

while (indexofsubarrayone < subarrayone) {

array[indexofmergedarray] = leftarray[indexofsubarrayone];

indexofsubarrayone++;

indexofmergedarray++;

}

// Copy the remaining elements of

// right[], if there are any

while (indexofsubarraytwo < subarraytwo) {

array[indexofmergedarray] = rightarray[indexofsubarraytwo];

indexofsubarraytwo++;

indexofmergedarray++;

}

}

// beg is for left index and end is

// right index of the sub-array

// of arr to be sorted */

void mergesort(int array[], int const beg, int const end)

{

if (beg >= end)

return; // Returns recursivly

int mid = beg + (end - beg) / 2;

mergesort(array, beg, mid);

mergesort(array, mid + 1, end);

merge(array, beg, mid, end);

}

// Function to print an array

void printarray(int arr[], int size)

{

for (int i = 0; i < size; i++)

cout << arr[i] << " ";

}

int main()

{

int arr[] = { 15, 9, 12, 2, 11, 18 };

int arrsize = sizeof(arr) / sizeof(arr[0]);

cout << "Array before sorting \n";

printarray(arr, arrsize);

mergesort(arr, 0, arrsize - 1);

cout << "\nArray after sorting \n";

printarray(arr, arrsize);

return 0;

}

merge_sort-implementation-img1

Create and Showcase Your Portfolio from Scratch!

Caltech PGP Full Stack DevelopmentExplore Program
Create and Showcase Your Portfolio from Scratch!

What Are the Advantages of the Merge Sort?

  • Merge sort can efficiently sort a list in O(n*log(n)) time.
  • Merge sort can be used with linked lists without taking up any more space.
  • A merge sort algorithm is used to count the number of inversions in the list.
  • Merge sort is employed in external sorting.

What Are the Drawbacks of the Merge Sort?

  • For small datasets, merge sort is slower than other sorting algorithms.
  • For the temporary array, mergesort requires an additional space of O(n).
  • Even if the array is sorted, the merge sort goes through the entire process.

Next Steps

Your next stop in mastering data structures should be the Insertion Sort Algorithm. Insertion sort is a basic sorting algorithm in which each item in the final sorted array (or list) is sorted one at a time.

If you're searching for a more in-depth understanding of software development that can help you carve out a successful career in the field, look no further. If that's the case, consider Simplilearn's Postgraduate Program in Full Stack Web Development, which is offered in collaboration with Caltech CTME, the world's largest technology education institution. This Post-Graduate Program will teach you how to master both front-end and back-end Java technologies, beginning with the fundamentals and progressing to the more advanced aspects of Full Stack Web Development. You will learn Angular, Spring Boot, Hibernate, JSPs, and MVC in this web development course to help you launch your career as a full-stack developer.

If you have any questions or need clarification on this tutorial about the "Merge Sort Algorithm," please drop them in the comments section below. Our expert team will review them and respond as soon as possible.

Become a Skilled Web Developer in Just 9 Months!

Caltech PGP Full Stack DevelopmentExplore Program
Become a Skilled Web Developer in Just 9 Months!

About the Author

Vaibhav KhandelwalVaibhav Khandelwal

Vaibhav Khandelwal is a proactive tech geek who's always on the edge of learning new technologies. He is well versed in competitive programming and possess sound knowledge of web development. He likes to read fictional and sci-fi novels and likes to play strategy games like chess.

View More
  • Disclaimer
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, and OPM3 are registered marks of the Project Management Institute, Inc.