written 2.8 years ago by |
Merge sort is a sorting algorithm that uses the divide, conquer and combine algorithm paradigm.
A] Divide: It means partitioning the n-element array to be sorted into two sub arrays of n/2 elements in each sub-array.
B] conquer: It means sorting the two arrays recursively using merge sort.
C] combine: It means merging two sorted sub array of size n/2 each to produce the sorted array of n elements.
Program:
include < stdio.h>
include <conio.h>
vid merge (int a [ ] , int, int, int);
void merge sort (int a [ ] , int , int ) ;
void main ( )
<
int a [10] , i, n, j , k;
print t ("in enter no of elements in array = ");
scan f ("%d",&n);
print f ("in enter elements of array ");
for (i=0; i<n; itt)</p>
<
print f ("in a [% d] = " ! i);
scan f (" % d " , & a [i]);
3
merge sort (a, o , n-1);
print t ("in sorted array = in ");
for (i = 0 ; i < n; itt)
<
print f ("+%d",a[i]);
3
getch ( ) ;
3
void merge (int a [ ] , int beg, int mid, int end)
<
int i = beg, j = mid + 1 , index = beg, temp [10], k; while (c i < 0 mid) & & (j <0 end) )
<
if (a [i] < a [j])
<
temp [index] = a [i];
itt;
3
else
temy [index] = a [j[;
jtt;
3
index tt ;
<
if (i > mid)
<
while (j <0 end)
<
temp [index] = a [j] ;
jtt;
index tt;
3
3 else
<
while (i < = mid)
<
temp [index] = a [i];
itt;
index tt;
3 3 for (k = beg i k < index ; ktt)
< a[k] = temp [k];
3
3
void merge sort (int a [ ] , int beg, int end)
<
int mid;
if (beg < end)
<
mid = (beg + end) / 2 ;
merge-sort (a, beg, mid);
merge - sort (a, mid + 1 , end);
merge (a , beg , mid , end);
3
3