Merge sort using C

programming

This program illustrates the merge sort using c program. Merge sort uses merge algorithm and partition algorithm to sort the given array of unsorted elements. Partition algorithm separates each element, and merge algorithm combines every thing and shows up the sorted format of the array in increasing or decreasing format as wished, here it is in increasing format. Have a look at the sample output and code.

Sample Output
Code
#include < stdio.h > #include < conio.h >
void merge(int[], int, int, int);
void partition(int[], int, int);
int main() {
  int arr[30];
  int i, size;
  printf("nt*********** Merge sort *********nn");
  printf("Enter total no. of elements : ");
  scanf("%d", & size);
  printf("Enter elements to be sorted:");
  for (i = 0; i < size; i++) {
    scanf("%d", & arr[i]);
  }
  partition(arr, 0, size - 1);

  printf("n*********************************n");
  printf("Sorted elements:");
  for (i = 0; i < size; i++)
    printf("%d ", arr[i]);
  getch();
  return 0;
}

void part(int arr[], int min, int max) {
  int mid;
  if (min < max) {
    mid = (min + max) / 2;
    partition(arr, min, mid);
    partition(arr, mid + 1, max);
    merge(arr, min, mid, max);
  }
}

void merge(int arr[], int min, int mid, int max) {
  int tmp[30];
  int i, j, k, m;
  j = min;
  m = mid + 1;
  for (i = min; j <= mid && m <= max; i++) {
    if (arr[j] <= arr[m]) {
      tmp[i] = arr[j];
      j++;
    } else {
      tmp[i] = arr[m];
      m++;
    }
  }
  if (j > mid) {
    for (k = m; k <= max; k++) {
      tmp[i] = arr[k];
      i++;
    }
  } else {
    for (k = j; k <= mid; k++) {
      tmp[i] = arr[k];
      i++;
    }
  }
  for (k = min; k <= max; k++)
    arr[k] = tmp[k];
}

Got any bugs?? Comment them below or contact me… And share it, if it is useful to you… 🙂

Catch me

Sidharth Patnaik

Blogger at Codermag
Tinkerer/Coder/Blogger
Catch me

Latest posts by Sidharth Patnaik (see all)

Related posts