Program to implement Merge Sort - TechnoHindi.Org

Latest

Saturday, August 8, 2020

Program to implement Merge Sort













#include <stdio.h> 
#include <conio.h> 
int a[50]; 
void merge ( int, int, int ); 
void merge_sort ( int, int ); 
void main() 
int num,i; 
clrscr(); 

printf ("Enter number of elements in array: \n"); 
scanf ("%d", &num); 

printf ("Enter the elements: \n"); 

for ( i=0; i<num; i++) 
scanf ("%d", &a[i]); 
merge_sort ( 0, num-1 ); 

printf ("Sorted array: \n"); 
for ( i=0; i<num; i++) 
printf ("%d \t", a[i]); 
getch(); 

void merge_sort ( int low, int high ) 
int mid; 

if( low < high ) 
mid = ( low + high ) / 2; 
merge_sort ( low, mid ); 
merge_sort ( mid+1, high ); 
merge ( low, mid, high ); 

void merge ( int low, int mid, int high ) 
int h, i, j, b[50], k; 

h = low; 
i = low; 
j = mid + 1; 

while (( h<=mid ) && ( j<=high )) 
if ( a[h] <= a[j] ) 
b[i] = a[h]; 
h++; 

else 
b[i] = a[j]; 
j++; 
i++; 

if ( h > mid ) 
for ( k=j; k<=high; k++ ) 
b[i] = a[k]; 
i++; 

else 
for ( k=h; k<=mid; k++ ) 
b[i] = a[k]; 
i++; 

for( k= low; k<= high; k++ ) 
a[k] = b[k]; 
}  
  1. Output :-

No comments:

Post a Comment