You are on page 1of 6

Sorting and searching techniques programs with solution

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: (Ascending order)


N=7
Array:6,3,1,4,2,7,5
Output:1,2,3,4,5,6,7
Selection sort
#include<stdio.h>
int main()
{
int n,t,i,j,min;
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++)
{
min=i;
for(j=i+1;j<n;j++)
{
if(a[j]<a[min])
{
min=j;
}
}
t=a[i];
a[i]=a[min];
a[min]=t;
}
for(i=0;i<n;i++)
{
printf("%d\t",a[i]);
}
return 0;
}

Input: (Ascending order)


N=7
Array:6,3,1,4,2,7,5
Output:1,2,3,4,5,6,7
Insertion 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=1;i<n;i++)
{
t=a[i];
j=i-1;
while(j>=0 && a[j]>t)
{
a[j+1]=a[j];
j=j-1;
}
a[j+1]=t;
}
for(i=0;i<n;i++)
{
printf("%d\t",a[i]);
}
return 0;
}

Input: (Ascending order)


N=7
Array:6,3,1,4,2,7,5
Output:1,2,3,4,5,6,7
Linear search
#include<stdio.h>
int main()
{
int n,search,i,found;
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]);
}
printf("enter the element to be searched");
scanf("%d",&search);
for(i=0;i<n;i++)
{
if(a[i]==search)
{
found=1;
}
}
if(found==1)
{
printf("%d is found at %d location",search,i);
}
else
{
printf("%d not found",search);
}
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

You might also like