In daily life, we need to store data for multiple purposes like Medical stores Grocery stores and etc. Storing data is not enough we also need efficient storing which can access very easily at the time of need so we can sort them.
If we want to store data that has the same type so we can use the concept of arrays.
Syntax of arrays:
//Array initialization
datatype array_name [array size] ;
int array[10];
//Array Declaration
datatype array_name [array size] ={elements};
int array[10]={1,2,3,4,5,6,7,8,9};
Searching in arrays:
We store our data for find when we needed .we can find data with the help of adding search operation in our program .
There are two types of searches in the array
- Sequential search
- Binary search
SORTING ARRAYS
#include<iostream>
using namespace std;
int main()
{
int a[10]={12,23,4,32,5,56,22,67,1,2};
int ci,i,j,temp;
for(i=0 ; i<10 ; i=i+1)
{
ci=i;
for(j=i+1 ; j<=10 ; j=j+1)
if(a[ci]>a[j])
ci=j;
temp=a[ci];
a[ci]=a[i];
a[i]=temp;
}
for(int k=0 ; k<10 ; k++)
{
cout<<a[k]<<"\t";
}
using namespace std;
int main()
{
int a[10]={12,23,4,32,5,56,22,67,1,2};
int ci,i,j,temp;
for(i=0 ; i<10 ; i=i+1)
{
ci=i;
for(j=i+1 ; j<=10 ; j=j+1)
if(a[ci]>a[j])
ci=j;
temp=a[ci];
a[ci]=a[i];
a[i]=temp;
}
for(int k=0 ; k<10 ; k++)
{
cout<<a[k]<<"\t";
}
}
SEQUENTIAL SEARCH
#include<iostream>
using namespace std;
int main()
{
int a[10]={23,4,56,78,65,32,1,78,65,32};
int search,i,found=0;
cout<<"Enter number for seqental search:";
cin>>search;
for(int i=0 ; i<10 ; i++)
{
if(a[i]==search)
{
found=1;
}
}
if(found==1)
{
cout<<"Number found"<<endl;
}
else
{
cout<<"Number not found"<<endl;
}
}
BINARY SEARCH
#include<iostream>
using namespace std;
int main()
{
int a[10]={1,2,3,4,5,6,7,8,9,10};
int first,last,mid,search;
first=0;
last=10-1;
mid=(first+last)/2;
cout<<"Enter number for search:"<<endl;
cin>>search;
while(first<=last)
{
mid=(first+last)/2;
if(a[mid]<search)
{
first=mid+1;
}
else if(a[mid]==search)
{
cout<<search<<":Is found at index number:"<<mid;
break;
}
else
{
last=mid-1;
}
}
if(first>last)
{
cout<<"Number not found"<<endl;
}
}
1 Comments
I tried to write like this (binary search logic) but i didn't get good result .
ReplyDelete