1.
C++ program for linear search
#include<iostream.h>
//int linearsearch(int [], int);
int main()
{
int array[10]={1,2,3,4,5,6,7,8,9,10};
int key;
cout<<"Enter the key element";
cin>>key;
//cout<<"Key Element Index value= "<<linearsearch(array,key);
return 0;
}
int linearsearch(int array[],int key)
{
int index=0;
int found=0;
do
{
if(array[index]==key)
found=1;
else
index++;
}while(found==0 && index<10); // 10 is size of array
if(found==0)
index=-1;
return index;
}
2. C++ program for binary search
#include<iostream.h>
int binarysearch(int [], int);
int main()
{
int array[10]={1,2,3,4,5,6,7,8,9,10};
int key;
cout<<"Enter the key element";
cin>>key;
cout<<"Key Element Index valu= "<<binarysearch(array,key);
return 0;
}
int binarysearch(int array[],int key)
{
int index,mid,left=0;
int right=9; // 9 = size of array - 1
int found=0;
do
{
mid=(left+right)/2;
if(array[mid]==key)
found=1;
else
{
if(array[mid]>key)
right=mid-1;
else
left=mid+1;
}
}while(found==0 && left<=right);
if(found==0)
index=-1;
else
index=mid;
return index;
3. C++ program for selection sort
#include<iostream.h>
void selection_sort(int[]);
int main()
{
int i;
int list[10]={3,2,4,9,8,5,6,7,0,1};
cout<<"List of Elements before sorted!!\n";
for(i=0;i<10;i++)
cout<<list[i]<<", ";
cout<<endl;
selection_sort(list);
cout<<"After Soring ...\n";
for(i=0;i<10;i++)
cout<<list[i]<<", ";
return 0;
}
void selection_sort(int list[])
{
int i,j, smallest, temp;
for(i=0;i<10;i++)
{
smallest=i;
for(j=i+1;j<10;j++)
{
if(list[j]<list[smallest])
smallest=j;
}
temp=list[smallest];
list[smallest]=list[i];
list[i]=temp;
}
}
4. C++ program for insertion sort
#include<iostream.h>
void insertion_sort(int[]);
int main()
{
int i;
int list[10]={3,2,4,9,8,5,6,7,0,1};
cout<<"List of Elements before sorted!!\n";
for(i=0;i<10;i++)
cout<<list[i]<<", ";
cout<<endl;
insertion_sort(list);
cout<<"After Soring ...\n";
for(i=0;i<10;i++)
cout<<list[i]<<", ";
return 0;
}
void insertion_sort(int list[])
{
int temp;
for(int i=1;i<10;i++)
{
temp=list[i];
for(int j=i; j>0 && temp<list[j-1];j--)
{ // work backwards through the array finding where temp should go
list[j]=list[j-1];
list[j-1]=temp;
}
}
}
5. C++ program for bubble sort
#include<iostream.h>
void bubble_sort(int[]);
int main()
{
int i;
int list[10]={3,2,4,9,8,5,6,7,0,1};
cout<<"List of Elements before sorted!!\n";
for(i=0;i<10;i++)
cout<<list[i]<<", ";
cout<<endl;
bubble_sort(list);
cout<<"After Soring ...\n";
for(i=0;i<10;i++)
cout<<list[i]<<", ";
return 0;
}
void bubble_sort(int list[])
{
int i,j,temp;
for(i=0;i<10; i++)
{
for(j=9;j>i; j--)
{
if(list[j]<list[j-1])
{
temp=list[j];
list[j]=list[j-1];
list[j-1]=temp;
}//swap adjacent elements
}
}
}