Announcing Bito’s free open-source sponsorship program. Apply now

Get high quality AI code reviews

Efficient Data Sorting: Implementing Merge Sort Algorithm in C Language

Table of Contents

Merge Sort is a highly efficient, stable, and comparison-based sorting algorithm. Its implementation in the C programming language showcases its divide-and-conquer strategy. This article delves into the fundamental principles of Merge Sort and provides a detailed walkthrough of its implementation in C.

Understanding Merge Sort

Conceptual Overview

Merge Sort divides an array into two halves, sorts each half, and then merges the sorted halves. This recursive approach ensures a time complexity of O(n log n), making it highly efficient for large datasets.

Algorithmic Steps

  1. Divide: Split the array into two halves.
  2. Conquer: Recursively sort each half.
  3. Merge: Combine the sorted halves into a single sorted array.

Implementing Merge Sort in C

Setting Up the Environment

Before diving into the code, ensure your C programming environment is set up. Any standard C compiler like GCC will suffice.

Code Walkthrough

#include <stdio.h>

void merge(int array[], int left, int mid, int right) {
    int n1 = mid - left + 1;
    int n2 = right - mid;

    // Temporary arrays
    int L[n1], R[n2];

    // Copy data to temp arrays L[] and R[]
    for (int i = 0; i < n1; i++)
        L[i] = array[left + i];
    for (int j = 0; j < n2; j++)
        R[j] = array[mid + 1 + j];

    // Merge the temp arrays back into array[left..right]
    int i = 0, j = 0, k = left;
    while (i < n1 && j < n2) {
        if (L[i] <= R[j]) {
            array[k] = L[i];
            i++;
        } else {
            array[k] = R[j];
            j++;
        }
        k++;
    }

    // Copy remaining elements of L[], if any
    while (i < n1) {
        array[k] = L[i];
        i++;
        k++;
    }

    // Copy remaining elements of R[], if any
    while (j < n2) {
        array[k] = R[j];
        j++;
        k++;
    }
}

void mergeSort(int array[], int left, int right) {
    if (left < right) {
        int mid = left + (right - left) / 2;

        // Sort first and second halves
        mergeSort(array, left, mid);
        mergeSort(array, mid + 1, right);

        merge(array, left, mid, right);
    }
}

// Function to print an array
void printArray(int A[], int size) {
    for (int i = 0; i < size; i++)
        printf("%d ", A[i]);
    printf("\n");
}

// Driver code
int main() {
    int arr[] = {12, 11, 13, 5, 6, 7};
    int arr_size = sizeof(arr) / sizeof(arr[0]);

    printf("Given array is \n");
    printArray(arr, arr_size);

    mergeSort(arr, 0, arr_size - 1);

    printf("\nSorted array is \n");
    printArray(arr, arr_size);
    return 0;
}

Explanation of the Code

  1. Function merge: This function takes a sub-array and two indices. It merges the two sorted halves.
  2. Function mergeSort: This recursive function divides the array and calls merge on the divided parts.
  3. Utility Functions: printArray to display the sorted array.

Conclusion

Merge Sort in C demonstrates the algorithm’s robustness and efficiency. Its divide-and-conquer methodology makes it a preferred choice for sorting large datasets. The provided code offers a clear understanding of how Merge Sort operates and can be utilized in various applications requiring sorted data

Picture of Sarang Sharma

Sarang Sharma

Sarang Sharma is Software Engineer at Bito with a robust background in distributed systems, chatbots, large language models (LLMs), and SaaS technologies. With over six years of experience, Sarang has demonstrated expertise as a lead software engineer and backend engineer, primarily focusing on software infrastructure and design. Before joining Bito, he significantly contributed to Engati, where he played a pivotal role in enhancing and developing advanced software solutions. His career began with foundational experiences as an intern, including a notable project at the Indian Institute of Technology, Delhi, to develop an assistive website for the visually challenged.

Written by developers for developers

This article was handcrafted with by the Bito team.

Latest posts

Mastering Python’s writelines() Function for Efficient File Writing | A Comprehensive Guide

Understanding the Difference Between == and === in JavaScript – A Comprehensive Guide

Compare Two Strings in JavaScript: A Detailed Guide for Efficient String Comparison

Exploring the Distinctions: == vs equals() in Java Programming

Understanding Matplotlib Inline in Python: A Comprehensive Guide for Visualizations

Top posts

Mastering Python’s writelines() Function for Efficient File Writing | A Comprehensive Guide

Understanding the Difference Between == and === in JavaScript – A Comprehensive Guide

Compare Two Strings in JavaScript: A Detailed Guide for Efficient String Comparison

Exploring the Distinctions: == vs equals() in Java Programming

Understanding Matplotlib Inline in Python: A Comprehensive Guide for Visualizations

Get Bito for IDE of your choice