Merge sort in C source code: This program provides you a simple sorting approach. This C program consists of an example code with explanation also. It is a type of sorting, which is rarely used sorting mechanism. An example program is given at the bottom.
- Insertion sort in C program [Insertion Algorithm code]
- Bubble sort program in C using arrays, function
MERGE SORT IN C
This C program is used to arrange or sort the array values in a same order as ascending order by comparing with the two values. For example if you have entered an elements like 6,9,1,-5,4 after merge sort the values will be -5,1,4,6,9.
Merge sort program:
Q: Write a C program for merge sort algorithm with an example and explanation.
//Header files #include<stdio.h> #include<conio.h> //Global declaration void merge(int da[],int q,int p,int r); void mergesort(int da[],int r,int p); void main() { //Program variables int da[10],j; printf("enter the input values for sorting"); //Display function for (j=0;j<10;j++) //Looping statement scanf("%d",&da[j]);//Getting input function mergesort(da,0,9); //Sort method printf("sorted data \n"); for (j=0;j<10;j++) printf("\n da[%d]=%d",j+1,da[j]); getch(); } // © http://students3k.com void mergesort(int da[10],int p,int r) { int q; if (p<r) { q=((p+r)/2); mergesort(da,p,q); mergesort(da,q+1,r); merge(da,p,q,r); } } // © http://students3k.com void merge(int da[10],int p,int q,int r) { int lw,k,hh,j,B[10]; lw=p;hh=q+1;k=p; while(lw<=q&&hh<=r) { if(da[lw]<=da[hh]) { B[k]=da[lw]; low++; } else { B[k]=da[hh]; hh++; } k++; } if (lw>q) for(j=hh;j<=r;j++) { B[k]=da[j]; k++; } // © http://students3k.com else for(j=lw;j<=q;j++) { B[k]=da[j]; k++; } for (j=p;j<=r;j++) da[j]=B[j]; }