0% found this document useful (0 votes)
38 views3 pages

Mergesort

The document describes the merge sort algorithm. It includes functions for merging, sorting, and displaying an array. The main function gets user input for the number of elements and values in an array, displays the unsorted array, calls the mergesort function to sort the array, and displays the sorted array. The mergesort function recursively divides the array into halves and calls the merge function to merge the sorted halves. The merge function merges two sorted halves into a single sorted array using a temporary array.

Uploaded by

happyskd1993
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
38 views3 pages

Mergesort

The document describes the merge sort algorithm. It includes functions for merging, sorting, and displaying an array. The main function gets user input for the number of elements and values in an array, displays the unsorted array, calls the mergesort function to sort the array, and displays the sorted array. The mergesort function recursively divides the array into halves and calls the merge function to merge the sorted halves. The merge function merges two sorted halves into a single sorted array using a temporary array.

Uploaded by

happyskd1993
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 3

Merge sort

#include<stdio.h> #include<conio.h> #define MAX 20 void mergesort(int a[],int low,int high); void merge(int a[],int beg,int mid,int end); void display(int a[],int num); void main() { int n,i,a[MAX]; clrscr(); printf("Enter the number of elements (<MAX )\n"); scanf("%d",&n); printf("Enter the elements\n"); for(i=0;i<n;i++) { scanf("%d",&a[i]); } printf("\nArray elements before sorting are:\n"); display(a,n); mergesort(a,0,n-1); printf("\nArray elements after sorting are:\n"); display(a,n); getch(); } void mergesort(int a[],int low,int high) { int mid; if(low<high) { mid=(low+high)/2; mergesort(a,low,mid); mergesort(a,mid+1,high); merge(a,low,mid,high); }

} void merge(int a[],int beg, int mid,int end) { int temp,b[MAX],left,right,i; left=beg; right=mid+1; temp=beg; while((left<=mid) && (right<=end)) { if(a[left]<a[right]) { b[temp]=a[left]; left=left+1; } else { b[temp]=a[right]; right=right+1; } temp=temp+1; } while(left<=mid) { b[temp]=a[left]; left=left+1; temp=temp+1; } while(right<=end) { b[temp]=a[right]; right=right+1; temp=temp+1; } for(i=beg;i<=end;i++) { a[i]=b[i]; } }

void display(int a[],int num) { int i; for(i=0;i<num;i++) printf("%d\t",a[i]); }

Output

You might also like