Life Hacks

# Write a program of the Merge Sort.

#include <iostream.h>

#include<conio.h>

int a; /* local variable */

void merge(int, int, int);

void merge_sort(int low, int high)

{

int mid; /* local variable */

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, k; /* local variable */

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++;

} /* End of while loop */

if(h > mid)

{

for(k = j; k <= high; k ++)

{

b[i] = a[k];

i++;

} /* End of for loop */

}

else

{

for(k = h; k <= mid; k ++)

{

b[i] = a[k];

i++;

} /* End of for loop */

}

for(k = low; k <= high; k ++)

{

a[k]=b[k];

} /* End of for loop */

}

void main( ) /* main start */

{

clrscr( );

int num, i; /* local variable */

cout << " Enter the number of the elements :";

cin >> num; // enter the no. of elements.

cout << " Enter the " << num << " numbers :”;

for(i = 1; i <= num; i ++) // enter the value of elements.

{

cin>>a[i] ;

} /* End of for loop */

merge_sort(1, num); // calling merge sort function.

cout << " Sorted list is : ";

for(i = 1; i <= num; i ++) // displays sorted elements list of the array.

{

cout << a[i] << " "; // prints sorted elements.

} /* End of for loop */

}

Output:- 