### Tutorial 4

Q-1. Binary Search.

#include<stdio.h>
#include<conio.h>
void main()
{
int array[10];
int i, j, N, temp, keynum;
int low,mid,high;
clrscr();
printf("Enter the value of N\n");
scanf("%d",&N);
printf("Enter the elements one by one\n");
for(i=0; i {
scanf("%d",&array[i]);
}
printf("Input array elements\n");
for(i=0; i {
printf("%d\n",array[i]);
}
/* Bubble sorting begins */
for(i=0; i< N ; i++)
{
for(j=0; j< (N-i-1) ; j++)
{
if(array[j] > array[j+1])
{
temp = array[j];
array[j] = array[j+1];
array[j+1] = temp;
}
}
}
printf("Sorted array is...\n");
for(i=0; i {
printf("%d\n",array[i]);
}
printf("Enter the element to be searched\n");
scanf("%d", &keynum);
/* Binary searching begins */
low=1;
high=N;
do
{
mid= (low + high) / 2;
if ( keynum < array[mid] )
high = mid - 1;
else if ( keynum > array[mid])
low = mid + 1;
} while( keynum!=array[mid] && low <= high); /* End of do- while */
if( keynum == array[mid] )
{
printf("SUCCESSFUL SEARCH\n");
}
else
{
printf("Search is FAILED\n");
}
} /* End of main*/

### Tutorial 3

Q-1: Write a program to implement sorting with Quick sort using Divide & Conquer method.

#include <stdio.h>
int split ( int*, int, int ) ;
void main( )
{
int arr[10] = { 11, 2, 9, 13, 57, 25, 17, 1, 90, 3 } ;
int i ;
void quicksort ( int *, int, int ) ;
quicksort ( arr, 0, 9 ) ;
printf ( "\nArray after sorting:\n") ;
for ( i = 0 ; i <= 9 ; i++ )
printf ( "%d\t", arr[i] ) ;
}
void quicksort ( int a[ ], int lower, int upper )
{
int i ;
if ( upper > lower )
{
i = split ( a, lower, upper ) ;
quicksort ( a, lower, i - 1 ) ;
quicksort ( a, i + 1, upper ) ;
}
}
int split ( int a[ ], int lower, int upper )
{
int i, p, q, t ;
p = lower + 1 ;
q = upper ;
i = a[lower] ;
while ( q >= p )
{
while ( a[p] < i )
p++ ;
while ( a[q] > i )
q-- ;
if ( q > p )
{
t = a[p] ;
a[p] = a[q] ;
a[q] = t ;
}
}

t = a[lower] ;
a[lower] = a[q] ;
a[q] = t ;

return q ;
}

Q-2: Write a program to implement sorting with Merge sort using Divide & Conquer method.

#include<stdio.h>

void getdata(int arr[],int n)
{
int i;
printf(“enter the data:");
for(i=0;i<n;i++)
{
scanf("%d",&arr[i]);
}
}
void display(int arr[],int n)
{
int i;
printf("  ");
for(i=0;i<n;i++)
{
printf("%d ",arr[i]);
}
getchar();
}
void sort(int arr[],int low,int mid,int high)
{
int i,j,k,l,b[20];
l=low;
i=low;
j=mid+1;
while((l<=mid)&&(j<=high))
{
if(arr[l]<=arr[j])
{
b[i]=arr[l];
l++;
}
else
{
b[i]=arr[j];
j++;
}

i++;
}
If(l>mid)
{
for(k=j;k<=high;k++)
{
b[i]=arr[k];
i++;
}
}
else
{
for(k=l;k<=mid;k++)
{
b[i]=arr[k];
i++;
}
}
for(k=low;k<=high;k++)
{
arr[k]=b[k];
}
}
void partition(int arr[],int low,int high)
{
int mid;
if(low<high)
{

mid=(low+high)/2;

partition(arr,low,mid);

partition(arr,mid+1,high);

sort(arr,low,mid,high);

}
}

void main()
{
int arr[20];
int n;
printf("Enter number of data:");
scanf("%d",&n);
getdata(arr,n);
partition(arr,0,n-1);
display(arr,n);
getchar();
}