1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
|
#include<stdio.h>
#define SIZE 10
#include<stdlib.h>
void MergeSort(int array[],int length);
void SortSubArray(int array[],int low,int high);
void Merge(int array[],int left,int middle1,int middle2,int right);
void Displayelement(int array[],int length);
void Displaysubarray(int array[],int left,int right);
int main()
{
int a[SIZE];
int i;
srand(1000);
for(i=0;i<SIZE;i++)
a[i]=rand()%90+10;
printf("UNSORTED ARRAY:");
Displayelement(a,SIZE);
MergeSort( a[],SIZE);
printf("SORTED ARRAY:");
Displayelement(a,SIZE);
return 0;
}
void Mergesort(int array[],int length)
{
SortSubArray(array,0,length-1);
}
void SortSubArray(int array[],int low,int high)
{
int middle1,middle2;
if(high-low>=1)
{
middle1=(high+low)/2;
middle2=middle1+1;
}
printf("\n ");
Displaysubarray(array,low,middle1);
printf("\n ");
Displaysubarray(array,middle2,high);
SortSubArray(array,low,middle1);
SortSubArray(array,middle2,high);
Merge(array[],low,middle1,middle2,high);
}
void merge(int array[],int left,int middle1,int middle2,int right)
{
int combinedindex=left;
int leftindex=left;
int rightindex=middle2;
int temp[SIZE];
while(leftindex<=middle1&&rightindex<=right)
{
if(array[leftindex]>array[rightindex])
{
temp[combinedindex]=array[rightindex];
rightindex++;
combinedindex++;
}
else
{
temp[combinedindex]=array[leftindex];
leftindex++;
combinedindex++;
}
}
while(leftindex<=middle1)
array[combinedindex++]=array[leftindex++];
while(rightindex<=right)
temp[combinedindex]=array[rightindex];
}
void Displayelement(int array[],int length)
{
Displaysubarray( array,0,length-1);
}
void Displaysubarray(int array[],int left,int right)
{
int i;
for(i=left;i<right;i++)
printf("%d",array[i]);
}
|