The C language implements the sequential and half lookup of the sequential table
- 2020-06-19 11:02:34
- OfStack
The example of this paper shares the specific code of C language to realize the sequential search and half-search of the sequence table, for your reference, the specific content is as follows
Sequential search:
#include <iostream>
using namespace std;
int SeqSearch(int r[],int n,int k)
{
r[0]=k;// The subscript 0 Use as a sentinel to store the number of queries
int i=n;
while(r[i]!=k)// You don't have to judge the subscript i Whether cross-border
{
i--;
}
return i;
}
int main()
{
int n;
cout<<" Please enter the number of array elements: "<<endl;
cin>>n;
int a[n+1];
cout<<" Please enter an array element: "<<endl;
for(int i=1;i<=n;i++)
{
cin>>a[i];
}
int k;
cout<<" Please enter the number to query: "<<endl;
cin>>k;
for(int i=1;i<=n;i++)
{
cout<<a[i]<<" ";
}
cout<<endl;
cout<<" The position of this number in the array is: ";
cout<<SeqSearch(a,n,k);
return 0;
}
Half search:
#include<iostream>
using namespace std;
int BinSearch1(int r[],int n,int k)// non-recursive
{
int low=1,high=n;// Set the search interval
while(low<=high)// If the interval exists
{
int mid=(low+high)/2;
if(k<r[mid])high=mid-1;// Find in the left half, go back while the 1 step
else if(k>r[mid])low=mid+1;
else return mid;
}
return 0;// Returns if the interval does not exist 0 , search failed
}
int BinSearch2(int r[],int low,int high,int k)// recursive
{
int mid=(low+high)/2;
if(low>high) return 0;
else
{
if(k<r[mid])BinSearch2(r,low,mid-1,k);
else if(k>r[mid])BinSearch2(r,mid+1,high,k);
else return mid;
}
}
int main()
{
int n;
cout<<" Please enter the number of array elements: ";
cout<<endl;
cin>>n;
int a[n+1];
cout<<" Please enter an array element: ";
cout<<endl;
for(int i=1;i<=n;i++)
{
cin>>a[i];
}
cout<<" Please enter the number you are looking for: ";
cout<<endl;
int k;
cin>>k;
cout<<" The position of the number in the array is: "<<endl;
cout<<BinSearch1(a,n,k);cout<<endl;
cout<<BinSearch2(a,1,n,k);
}