Professional Documents
Culture Documents
Bubble sort
#include<stdio.h>
int main()
{
int n,t,i,j;
printf("enter the size of an array");
scanf("%d",&n);
int a[n];
for(i=0;i<n;i++)
{
printf("enter the values ");
scanf("%d",&a[i]);
}
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(a[i]>a[j])
{
t=a[i];
a[i]=a[j];
a[j]=t;
}
}
}
for(i=0;i<n;i++)
{
printf("%d\t",a[i]);
}
return 0;
}
Input:
N=7
Array:6,3,1,4,2,7,5
Search element:4
Output:4 is found at position 3
Binary search
#include<stdio.h>
int main()
{
int i,low,high,mid,n,search;
printf("enter the size of an array");
scanf("%d",&n);
int a[n];
for(i=0;i<n;i++)
{
printf("enter the values in sorted order");
scanf("%d",&a[i]);
}
printf("enter the element to be searched");
scanf("%d",&search);
low=0;
high=n-1;
mid=(low+high)/2;
while(low<=high)
{
if(search>a[mid])
{
low=mid+1;
}
else if(search==a[mid])
{
printf("%d is found at %d location",search,mid);
break;
}
else
{
high=mid-1;
}
mid=(low+high)/2;
}
if(low>high)
{
printf("%d not found",search);
}
return 0;
}
Input: (sorted array)
N=7
Array:1,2,3,4,5,6,7
Search element:4
Output:4 is found at position