Saturday, 28 January 2017

Merge sort in C programming example with explanation ~ mkniit ~ gniitsolution

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.


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.
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
//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();
 }
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);
   }
 }
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++;
     }
   else
   for(j=lw;j<=q;j++)
    {
      B[k]=da[j];
      k++;
    }
   for (j=p;j<=r;j++)
     da[j]=B[j];
 }

2 comments: