< Nafees />
github
  • Assignments - DSA
  • Long Integer Operations
  • OOP
    • Introduction
    • Implementation
  • Sorting Algorithms
    • Selection Sort
    • Bubble Sort
    • Insertion Sort
    • Shell Sort
    • Shuffle
    • Merge Sort
    • Convex Hull
    • Quick sort
    • System Sort
    • Heap-Sort
  • Binary Search
  • Binary Search By Recursion
  • Two-Pointer
  • String
  • LeetCode 75
    • Array/String
    • Hash Map
    • BST
    • Binary Search
  • Top Interview 150
    • Linked-List
  • Leetcode Programming Skill
    • Math
  • Leetcode 75
  • 🤡Leet Code Extra
  • Arrays
    • 1-D Array
    • 2-D Arrays
  • 👨‍🍳Basic Math - Codechef
  • ☠️Recursion
  • 😁Public Member Functions
    • Strings Functions
  • 👾Linked List
    • What's Linked List & Implementation?
      • Singly Linked List
      • Doubly Linked List
    • Problems
  • 📚Stack
    • What's Stack & Implementation?
      • Stack Using Array
      • Stack using LL
    • Problems
  • 🏧Queue
    • What's Queue & Implementation?
      • Simple Queue
      • Queue using LL
      • Circular Queue
      • Deque using Linked List
      • STL Deque
    • Problems
  • 🏧Priority Queue
    • What's Priority Queue & Implementation
      • OrderedArrayMaxPQ.Java
      • Maximum-Oriented PQ using Binary Heap
      • Minimum-Oriented PQ using Binary Heap
    • Problems
  • 🗓️Hash Table
    • What's Hash Table & Implementation
      • ST - Seperate Chaining
      • ST - Linear Probing
    • Problems
  • 🎴Symbol Table
    • What's Symbol Table and implementation
      • ST Using Binary search (ordered array)
      • ST Using Binary Search Tree
      • ST Using Left-Leaning Red-Black Tree
      • ST Using Hash Table
    • Problems
  • 🔗Union-Find (Dynamic Connectivity problem)
    • What is a Union Find Data Structure?
    • Implementation
  • 🎋Binary Tree
    • What's Binary Tree & Implementation?
      • Traversal
      • Red-Black BST
  • 🌴Trie
    • What's Trie & Implementation?
    • Problems
  • 😎Project
    • Expression Evaluation
Powered by GitBook
On this page
  • How does Merge Sort work?
  • Applications of Merge Sort:
  • Advantages of Merge Sort:
  • Drawbacks of Merge Sort:
  • Q1: Merge Sort
  • Article
  • Code Dry Run
  • Space Complexity = O(n)
  • Time Complexity = O(n log n)

Was this helpful?

  1. Sorting Algorithms

Merge Sort

PreviousShuffleNextConvex Hull

Last updated 10 months ago

Was this helpful?

The merge sort function is a very efficient sorting algorithm. It is a divide-and-conquer algorithm, which means it breaks down the problem into smaller and smaller subproblems until they can be solved easily. This makes it a very efficient algorithm for sorting large arrays.

  • Tuned mergesort for objects. - where space doesn't matter

How does Merge Sort work?

Merge sort is a recursive algorithm that continuously splits the array in half until it cannot be further divided i.e., the array has only one element left (an array with one element is always sorted). Then the sorted subarrays are merged into one sorted array.

Applications of Merge Sort:

  • Sorting large datasets: Merge sort is particularly well-suited for sorting large datasets due to its guaranteed worst-case time complexity of O(n log n).

  • External sorting: Merge sort is commonly used in external sorting, where the data to be sorted is too large to fit into memory.

  • Custom sorting: Merge sort can be adapted to handle different input distributions, such as partially sorted, nearly sorted, or completely unsorted data.

Advantages of Merge Sort:

  • Stability: Merge sort is a stable sorting algorithm, which means it maintains the relative order of equal elements in the input array.

  • Guaranteed worst-case performance: Merge sort has a worst-case time complexity of O(N logN), which means it performs well even on large datasets.

  • Parallelizable: Merge sort is a naturally parallelizable algorithm, which means it can be easily parallelized to take advantage of multiple processors or threads.

Drawbacks of Merge Sort:

  • Space complexity: Merge sort requires additional memory to store the merged sub-arrays during the sorting process.

  • Not in-place: Merge sort is not an in-place sorting algorithm, which means it requires additional memory to store the sorted data. This can be a disadvantage in applications where memory usage is a concern.

  • Not always optimal for small datasets: For small datasets, Merge sort has a higher time complexity than some other sorting algorithms, such as insertion sort. This can result in slower performance for very small datasets.

Space Complexity = O(n)

Time Complexity = O(n log n)

The time complexity of Merge Sort isθ(Nlog(N)) in all 3 cases (worst, average, and best) as merge sort always divides the array into two halves and takes linear time to merge two halves.

#include <iostream>
using namespace std;

// A function to merge two sorted subarrays into one
void Merging(int *arr, int mid, int s, int e) {

    int len1 = mid-s+1;
    int len2 = e-mid;
    
    // Create temporary arrays to store the subarrays
    int *first = new int[len1];
    int *second = new int[len2];

    int mainArrayIndex = s;

    // Copy the data from the original array to the temporary arrays
    for (int i = 0; i < len1; i++)
        first[i] = arr[mainArrayIndex++];

    for (int i = 0; i < len2; i++)
        second[i] = arr[mainArrayIndex++];
    
    // Initialize the indices for the subarrays and the merged array
    int i = 0, j = 0, k = s;
    
    // Merge the subarrays by comparing their elements
    while (i < len1 && j < len2){
        if(first[i] < second[j])
            arr[k++] = first[i++];
        else
            arr[k++] = second[j++];
    }

    // Copy the remaining elements of the subarrays if any
    while (i < len1)
        arr[k++] = first[i++];
    
    while (j < len2)
        arr[k++] = second[j++];
   
}

void mergeSort(int *arr, int s, int e) {
    if(s >= e)
        return;
    int mid = s+(e-s)/2;

    // Recursively sort the left and right halves of the array
    mergeSort(arr, s, mid);

    mergeSort(arr, mid+1, e);
  
    if (arr[mid] <= arr[mid + 1])
               return;

    Merging(arr, mid, s, e);
}

int main(){
    int n = 7;
    int arr[n] = { 3, 4, 1, 6, 2, 5, 7 };
    mergeSort(arr, 0, n-1);

    for (int i = 0; i < n; i++){
        cout << arr[i] << ' ';
    }
}

Q1:

Code

Merge Sort
Article
Dry Run
Inversion Count Problem
4MB
Mergesort.pdf
pdf
Page cover image