C PROGRAMMING PROGRAM • ARRAYS, SEARCHING & SORTING

Sort an Array Using Merge Sort

Learn how to sort an array using merge sort using a clear C program.

AdvancedMerge sortDivide and conquerRecursion

PROBLEM UNDERSTANDING

Input and expected output

Sample input
7
38 27 43 3 9 82 10
Sample output
3 9 10 27 38 43 82

COMPLETE C PROGRAM

Complete C implementation

merge-sort.c
Open in compiler
#include <stdio.h>

void merge(int values[], int left, int middle, int right)
{
    int temporary[100], first = left, second = middle + 1, count = 0;
    while (first <= middle && second <= right)
        temporary[count++] = values[first] <= values[second] ? values[first++] : values[second++];
    while (first <= middle) temporary[count++] = values[first++];
    while (second <= right) temporary[count++] = values[second++];
    for (int index = 0; index < count; index++) values[left + index] = temporary[index];
}

void mergeSort(int values[], int left, int right)
{
    if (left < right) {
        int middle = left + (right - left) / 2;
        mergeSort(values, left, middle);
        mergeSort(values, middle + 1, right);
        merge(values, left, middle, right);
    }
}

int main(void)
{
    int size, values[100];

    scanf("%d", &size);
    if (size < 1 || size > 100) return 1;
    for (int index = 0; index < size; index++) scanf("%d", &values[index]);
    mergeSort(values, 0, size - 1);
    for (int index = 0; index < size; index++) printf("%d%c", values[index], index == size - 1 ? '\n' : ' ');
    return 0;
}

GUIDED CODE TOUR • NOT LIVE EXECUTION

Study the program line by line

Use the real compiler button above to run and debug with different inputs.

CURRENT STEP

Select Start to walk through the important lines.

SELECTED LINE

No line selected

EXPECTED OUTPUT FOR THE SAMPLE

3 9 10 27 38 43 82
0%Step 0 of 0

PROGRAM EXPLANATION

Algorithm and explanation

  1. Read the required input values.
  2. Recursively split the array, then merge each pair of sorted halves.
  3. Display the computed result.

Recursively split the array, then merge each pair of sorted halves.

EFFICIENCY

Time and space complexity

Time complexity

O(n log n)

Auxiliary space

O(n)

DEBUGGING CHECKLIST

Common mistakes

Check this

Use the correct format specifier for every variable.

Check this

Initialize variables before using their values.

Check this

Check braces, semicolons and input order carefully.

Try it yourself

Practice: Run the program with the sample input, predict its output, and then test one boundary case of your own.