Friday, January 9, 2015

Merge Sort in DSA



/*Title   :   Merge sort*/

#include<stdio.h>
#include<conio.h>
#include "array.h"

#define MAX 10//its value remains constant

void merge(int *arr, int *temp, int low, int mid, int high);//function prototype for merge sorting

/*function for merge sorting*/
void m_sort(int *arr, int *temp, int low, int high)
 {
   int mid;
   if(high>low)
    {
      mid = (low+high)/2;//middle element
      m_sort(arr,temp,low,mid);
      m_sort(arr,temp,mid+1,high);
      merge(arr,temp,low,mid+1,high);
    }
 }

void merge(int *arr, int *temp, int low, int mid, int high)
 {
   int i,end,num,pos;
   end = mid-1;
   pos = low;
   num = high-low+1;
   while((low<=end) && (mid<=high))
    {
      if(arr[low]<=arr[mid])
       {
temp[pos] = arr[low];
pos = pos + 1;
low = low + 1;
       }
      else
       {
temp[pos] = arr[mid];
pos = pos + 1;
mid = mid + 1;
       }
    }
   while(low<=end)
    {
      temp[pos] = arr[low];
      low = low + 1;
      pos = pos + 1;
    }
   while(mid<=high)
    {
      temp[pos] = arr[mid];
      mid = mid + 1;
      pos = pos + 1;
    }
   for(i=0;i<num;i++)
    {
      arr[high] = temp[high];
      high = high - 1;
    }
 }
void main()
 {
   int num,arr[MAX],temp[MAX],i;
   clrscr();
   printf("\nEnter the number of elements :");
   scanf("%d",&num);
   if(num>MAX)
    printf("\nArray out of bound!");
   else
    {
      for(i=0;i<num;i++)
      scanf("%d",&arr[i]);    

      m_sort(arr,temp,0,num);
      printf("\nThe list after sorting is :");

      for(i=0;i<num;i++)
      printf("%d",arr[i]);
    }
   getch();
 }




/*output of the program*/
How many elements:
5
Enter the element of array
4
69
21
3
2
The number after selection sorting are:
2
3
4
21
69

for more codes you can Visit http://codesofprogramming.blogspot.in/

No comments:

Post a Comment