OS-(I) Assignment 1: Set B- 1)

(1) Implement the C program to accept n integers to be sorted. Main function creates child process using fork system call. Parent process sorts the integers using bubble sort and waits for child process using wait system call. Child process sorts the integers using insertion sort.

Solution:
#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>

void bubble_sort(int [],int);
void insertion_sort(int [],int);
int main()
{
int i,j,n,*status=NULL,arr[30];
pid_t pid;
printf("\nEnter the number of elements:");
scanf("%d",&n);
for(i=0;i<n;i++)
    scanf("%d",&arr[i]);
}
pid=fork();
if(pid==0)
{
    printf("\n\t This is child process. ");
    printf("\n\t My process id is : %d", getpid());
       printf("\n\t My Parent process id is : %d", getppid());
    insertion_sort(arr,n);
    printf("\nInsertion ort");  
    for(i=0;i<n;i++)
    printf("    %d",arr[i]);
    printf("\n\n");
}
else
{
    printf("\n\n\t Parent process resumed after the execution of child process with PID %d", pid);
     printf("\n\t My process id is : %d", getpid());
   printf("\n\t My Parent process id is : %d", getppid());
            bubble_sort(arr,n);
            printf("\nBubble Sort:");
            for(i=0;i<n;i++)
printf("    %d",arr[i]);
    printf("\n\n");
    pid=wait(status);
}
}
void bubble_sort(int *a,int n)
{
    int i,j,temp;
    for(i=0;i<n;i++)
    {
        for(j=0;j<n-i-1;j++)
        {
            if(a[j]>a[j+1])
            {
                temp=a[j];
a[j]=a[j+1];
                a[j+1]=temp;
            }
        }
    }
}
void insertion_sort(int *a,int n)
{
    int i,j,temp;
    for(i=1;i<n;i++)
{
temp=a[i];
for(j= i-1; j>=0 && temp<a[j]; j--)
a[j+1]=a[j];
a[j+1]=temp;
}
}

0 Comments:

Post a Comment