Sunday, July 31, 2011

Algorithm of Merging Sort using c/c++ with source code

Merging is the process of combining two or more sorted files into a third sorted file.

Merge sort is based on divide and conquer paradigm.

Source Code of Merging Sort Using c/c++ is as follow

/**IDE : CODE BLOCKS 10.05
PROGRAM : merge.cpp
*/
#include <iostream>
#include <cstdlib>
#define size 10
using namespace std;
void merge(int *arr,int f1,int l1,int f2,int l2)
{
     int arr1[size],len1,len2,ap1=f1,ap2=f2,ap3;
     for(ap3=0;ap1<=l1 && ap2<=l2;ap3++)
     {
          if(arr[ap1]<arr[ap2])
               arr1[ap3]=arr[ap1++];
          else
               arr1[ap3]=arr[ap2++];
     }
     while(ap1<=l1)
          arr1[ap3++]=arr[ap1++];
     while(ap2<=l2)
          arr1[ap3++]=arr[ap2++];
     for(int i=f1;i<=l2;i++)
     {
          arr[i]=arr1[i-f1];
     }
}
void mergesort(int *arr,int first,int last)
{
     int len=last-first+1;
     if(len==1) return;
     int mid;
     mid=(first+last)/2;
     mergesort(arr,first,mid);
     mergesort(arr,mid+1,last);
     merge(arr,first,mid,mid+1,last);
}
int  main()
{
     int arr[size],i;
     cout<<"Enter 10 numbers randomly :-"<<endl;
     for(i=0;i<size;i++)
          cin>>arr[i];
     mergesort(arr,0,size-1);
     cout<<endl<<"After sorting"<<endl;
     for(i=0;i<size;i++)
          cout<<arr[i]<<'\t';
     return 0;
}

Drops comments if any correction required !!!

No comments:

Post a Comment