What Is Merge Sort in Data Structure in C?

//

Angela Bailey

When it comes to sorting algorithms in data structure, one of the most efficient and widely used algorithms is Merge Sort. Merge Sort is a divide-and-conquer algorithm that recursively divides the input array into smaller subarrays, sorts them, and then merges them back together to obtain a sorted output.

Let’s take a closer look at how Merge Sort works:

Divide and Conquer

The first step in Merge Sort is to divide the input array into two equal halves. This process is repeated until we have subarrays that contain only one element. At this point, each subarray is considered sorted.

To divide an array into two halves, we calculate the middle index using the formula:

mid = (left + right) / 2

where left represents the leftmost index of the current subarray and right represents the rightmost index.

Merge Operation

The next step in Merge Sort involves merging two sorted subarrays back together to form a single sorted array. This process continues until all subarrays are merged, resulting in a completely sorted array.

To merge two sorted subarrays, we compare elements from both subarrays and place them in their correct order in a temporary array. We keep track of the current indices for both subarrays and increment them accordingly as elements are placed in the temporary array.

Merge Function:


void merge(int arr[], int left, int mid, int right) {
    int i, j, k;
    int n1 = mid - left + 1;
    int n2 = right - mid;
    int L[n1], R[n2];
    for (i = 0; i < n1; i++)
      L[i] = arr[left + i];
    for (j = 0; j < n2; j++)
      R[j] = arr[mid + 1 + j];
    i = 0;
    s;j = 0;
 &nsbp;s s;k = left;
 
 

while (i < n1 && j < n2) {
if (L[i] <= R[j]) {
arr[k] = L[i];
i++;
} else {
arr[k] = R[j];
j++;
}

k++;
}

After merging the subarrays, the temporary array contains the sorted elements. We then copy these elements back into the original array.

Merge Sort Algorithm:

The Merge Sort algorithm can be implemented using a recursive function:

Merge Sort Function:

```c
void mergeSort(int arr[], int left, int right) {
if (left < right) { int mid = left + (right - left) / 2; mergeSort(arr, left, mid); mergeSort(arr, mid + 1, right); merge(arr, left, mid, right); } } ```

Now that we have a clear understanding of how Merge Sort works, let's analyze its time complexity. Merge Sort has a time complexity of O(n log n), where n represents the number of elements in the input array. This makes it more efficient than other sorting algorithms like Bubble Sort or Insertion Sort.

In conclusion, Merge Sort is a powerful sorting algorithm that utilizes the divide-and-conquer approach to efficiently sort an array. Its time complexity and stability make it a popular choice for various applications. By understanding its inner workings and implementing it in C or any other programming language, you can improve your programming skills and tackle complex sorting tasks with ease.