C Program to implement Merge Sort using Recursive Approach - BunksAllowed

BunksAllowed is an effort to facilitate Self Learning process through the provision of quality tutorials.

Random Posts

C Program to implement Merge Sort using Recursive Approach

Share This
Source Code
#include<stdlib.h> #include<stdio.h> void merge(int *list, int l, int m, int r) { int i, j, k; int n1 = m - l + 1; int n2 = r - m; /* create temp arrays */ int L[n1], R[n2]; /* Copy data to temp arrays L[] and R[] ; Basically L[] denotes the left subarray and R[] denotes right subarray*/ for (i = 0; i < n1; i++) L[i] = list[l + i]; for (j = 0; j < n2; j++) /*divide method for divide and conquer algorithm*/ R[j] = list[m + 1+ j]; /* Merge the temp arrays back into arr[l..r]*/ i = 0; // Initial index of first subarray j = 0; // Initial index of second subarray k = l; // Initial index of merged subarray while (i < n1 && j < n2) { if (L[i] <= R[j]) { list[k] = L[i]; i++; /*place the elements in their exact position based on comparisions*/ } /*conquer method which is basically combine*/ else { list[k] = R[j]; j++; } k++; } /* Copy the remaining elements of L[], if there are any */ while (i < n1) { list[k] = L[i]; i++; k++; } /* Copy the remaining elements of R[], if there are any */ while (j < n2) { list[k] = R[j]; j++; k++; } } /* l is for left index and r is right index of the sub-array of arr to be sorted */ void mergesort(int *list, int l, int r) { if (l < r) { // Same as (l+r)/2, but avoids overflow for large l and h int m = l+(r-l)/2; // Sort first and second halves mergesort(list, l, m); mergesort(list, m+1, r); merge(list, l, m, r); } } void display(int *list, int size) { int i; for (i=0; i < size; i++) printf("%d|", list[i]); } int main() { int i, low, high, n; int *list; printf("\nenter the no of elements:"); scanf("%d", &n); list=(int *)malloc(sizeof(int) * n); for(i = 0;i < n; i++) scanf("%d", &list[i]); low = 0; high = n - 1; mergesort(list, low, high); printf("\nsorted list is:\n"); display(list, n); return 0; }

Happy Exploring!

No comments:

Post a Comment