Code:
#include<stdio.h>
#include<conio.h>
void insertsorted(int *,int *,int);
void mergesort(int *,int,int *,int, int *);
int checksort(int *, int *);
main()
{
int item,n,choice,l,b,k,i,m,p,checkcounter;
char rerun;
point1:
printf("\n Enter your choice for array operations\n\n");
printf("\n\t5. Insert in sorted array");
printf("\n\t10. Merge two sorted array");
printf("\n\t11. Exit");
printf("\n\n Your selected choice is: ");
scanf("%d",&choice);
if((choice<1)||(choice>11))
{
printf("Wrong value entered; please try again");
getch();
system("cls");
goto point1;
}
if(choice==11)
{
printf("\n Thanks for using the program\n Have a great day!!!");
getch();
exit(0);
}
printf("\nEnter element size: ");
scanf("%d",&n);
int A[n];
printf("\nEnter %d elements of the array: \n",n);
for(i=0;i<n;i++)
scanf("%d",&A[i]);
printf("\nThe elements of arrays are: ");
for(i=0;i<n;i++)
printf("%d\t",A[i]);
if(choice==10)
{
printf("\nEnter element size of second array");
scanf("%d",&m);
p=m+n;
int B[m],sorted[p];
printf("\nEnter %d elements of the array: \n",m);
for(i=0;i<m;i++)
scanf("%d",&B[i]);
printf("\nThe elements of arrays are: ");
for(i=0;i<m;i++)
printf("%d\t",B[i]);
checkcounter=checksort(A,&n);
if(checkcounter==-1)
{
printf("\n\n The element of this array are not sorted, please insert a sorted array");
printf("\n Thanks for using the program\n Have a great day!!!");
getch();
exit(0);
}
checkcounter=checksort(B,&m);
if(checkcounter==-1)
{
printf("\n\n The element of this array are not sorted, please insert a sorted array");
printf("\n Thanks for using the program\n Have a great day!!!");
getch();
exit(0);
}
mergesort(A,n,B,m,sorted);
printf("\nThe new array is:\n");
for(i=0;i<p;i++)
{
printf("%d\t",sorted[i]);
}
getch();
}
switch (choice)
{
case 5:
checkcounter=checksort(A,&n);
if(checkcounter==-1)
{
printf("\n The element of this array are not sorted, please insert a sorted array");
break;
}
printf("\nEnter number to be inserted in array");
scanf("%d",&item);
insertsorted(A,&n,item);
printf("\nThe new array is:\n");
for(i=0;i<n;i++)
{
printf("%d\t",A[i]);
}
break;
case 10:
break;
default:
printf("\n Wrong option selected; please try again");
getch();
system("cls");
goto point1;
}
getch();
system("cls");
printf("\n Do you want to re run the program??? (y to continue; any other key to exit): ");
fflush(stdin);
scanf("%c",&rerun);
if(rerun=='y')
{goto point1;}
system("cls");
printf("\n Thanks for using the program\n Have a great day!!!");
getch();
}
void insertsorted(int *a, int *n, int item)
{
int k;
k=*n-1;
while((item<a[k])&&(k>=0))
{
a[k+1]=a[k];
a--;
}
a[k+1]=item;
(*n)++;
}
void mergesort(int *a, int m, int *b, int n, int *c)
{
int na, nb, nc;
na=nb=nc=0;
while((na<m) && (nb<n))
{
if(a[na]<b[nb])
c[nc]=a[na++];
else
c[nc]=b[nb++];
nc++;
}
if(na==m)
{
while(nb<n)
c[nc++]=b[nb++];
}
else if (nb==n)
{
while(na<m)
c[nc++]=a[na++];
}
}
int checksort(int *a, int *n)
{
int i=0;
while(i<*n)
{
if(a[i]>a[i+1])
{
return -1;
}
i++;
}
return 0;
}