What comments and where would you enter into my program to help you understand i
ID: 3809301 • Letter: W
Question
What comments and where would you enter into my program to help you understand it?
#include<stdio.h>
void mergesort(int a[],int i,int j);
void merge(int a[],int i1,int j1,int i2,int j2);
int main()
{
int a[30],n,i;
printf("Enter no of elements:");
scanf("%d",&n);
printf("Enter array elements:");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
mergesort(a,0,n-1);
printf(" Sorted array is :");
for(i=0;i<n;i++)
printf("%d ",a[i]);
return 0;
}
void mergesort(int a[],int i,int j)
{
int mid;
if(i<j)
{
mid=(i+j)/2;
mergesort(a,i,mid);
mergesort(a,mid+1,j);
merge(a,i,mid,mid+1,j);
}
}
void merge(int a[],int i1,int j1,int i2,int j2)
{
int temp[50]; //array used for merging
int i,j,k;
i=i1; //beginning of the first list
j=i2; //beginning of the second list
k=0;
while(i<=j1 && j<=j2)
{
if(a[i]<a[j])
temp[k++]=a[i++];
else
temp[k++]=a[j++];
}
while(i<=j1)
temp[k++]=a[i++];
while(j<=j2)
temp[k++]=a[j++];
//Transfer elements from temp[] back to a[]
for(i=i1,j=0;i<=j2;i++,j++)
a[i]=temp[j];
}
Explanation / Answer
#include<stdio.h>
//Function prototypes
void mergesort(int a[],int i,int j);
void merge(int a[],int i1,int j1,int i2,int j2);
int main()
{
int a[30],n,i;
printf("Enter no of elements:");
scanf("%d",&n); //input value of n
printf("Enter array elements:");
for(i=0;i<n;i++)
scanf("%d",&a[i]); //input n elements in array
mergesort(a,0,n-1); //call mergesort with array name, first index and last index in the array
printf(" Sorted array is :");
for(i=0;i<n;i++)
printf("%d ",a[i]); // display sorted array
return 0;
}
void mergesort(int a[],int i,int j)
{
int mid;
if(i<j) //do recursive calling to merge sort until i = j(single element in the list)
{
mid=(i+j)/2; //mid = (first index + last index )/2
mergesort(a,i,mid); // recursive function call from 1st element to mid
mergesort(a,mid+1,j); //recursive function call from mid+1 element to last element
merge(a,i,mid,mid+1,j); //call merge function
}
}
void merge(int a[],int i1,int j1,int i2,int j2)
{
int temp[50]; //array used for merging
int i,j,k;
i=i1; //beginning of the first list
j=i2; //beginning of the second list
k=0;
while(i<=j1 && j<=j2)
{
if(a[i]<a[j]) //select smaller element a[i] from two lists
temp[k++]=a[i++]; //and place it in temp
else
temp[k++]=a[j++]; // smaller element is a[ j]
}
while(i<=j1) //fill temp array with remaining elements of list1
temp[k++]=a[i++];
while(j<=j2)
temp[k++]=a[j++]; //fill temp with remaining elements of list2
//Transfer elements from temp[] back to a[]
for(i=i1,j=0;i<=j2;i++,j++)
a[i]=temp[j];
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.