merge sort in c

merge sort in c
/*
Example: merge sort in C language
*/

#include <stdio.h>
#include <stdlib.h>

// Merge two sub arrays L and M into arr
void merge(int arr[], int p, int q, int r) {

  // create L ← A[p..q] 和  M ← A[q+1..r]
  int n1 = q - p + 1;
  int n2 = r - q;

  int L[n1], M[n2];

  for (int i = 0; i < n1; i++)
    L[i] = arr[p + i];
  for (int j = 0; j < n2; j++)
    M[j] = arr[q + 1 + j];

  int i, j, k;
  i = 0;
  j = 0;
  k = p;

  // Before reaching the end of L or M, select the larger elements in the elements L and M and place them in A[p. r].
  while (i < n1 && j < n2) {
    if (L[i] <= M[j]) {
      arr[k] = L[i];
      i++;
    } else {
      arr[k] = M[j];
      j++;
    }
    k++;
  }

  // When the elements in L or M are exhausted, remove the remaining elements and put A[p. r]
  while (i < n1) {
    arr[k] = L[i];
    i++;
    k++;
  }

  while (j < n2) {
    arr[k] = M[j];
    j++;
    k++;
  }
}

// Divide the array into two subarrays, sort them, and merge them
void mergeSort(int arr[], int l, int r) {
  if (l < r) {

    // m is the cut-off point that divides the array into two arrays
    int m = l + (r - l) / 2;

    mergeSort(arr, l, m);
    mergeSort(arr, m + 1, r);

    // Merge sorted subarrays
    merge(arr, l, m, r);
  }
}

// Print the array
void printArray(int arr[], int size) {
  for (int i = 0; i < size; i++)
    printf("%d ", arr[i]);
  printf("\n");
}

int main() {
  int arr[] = {3,6,19,11,21,12,7,5,9};
  int size = sizeof(arr) / sizeof(arr[0]);

  mergeSort(arr, 0, size - 1);

  printf("Sorted array: \n");
  printArray(arr, size);
}
Source‮l.www:‬autturi.com

output:

Sorted array:
3 5 6 7 9 11 12 19 21

Process returned 0 (0x0)   execution time : 0.544 s
Press any key to continue.
Created Time:2017-08-29 09:35:25  Author:lautturi