Searching Data from server and displaying it on the users screen is much easier than you think . I am going to discuss Binary Search and Linear search algorithm .
Binary Search
Binary Search algorithm divides data in two parts left and right and search in the sorted data. Sorted data should be provided to this algorithm.
code....
// Binary searth algorithm.
#include<stdio.h>
int main(){
int a[5]={2,4,6,8,12},n=5,target=8,first=0,last=0,middle=0,step=0;
first = 0;
last = n-1;
middle = (first + last)/2;
while(last>=first){
step++;
if(a[middle] > target){
last = middle-1;
}
else if (a[middle] == target){
printf("Found at index : %d",middle);
break;
}
else{
first = middle+1;
}
middle = (first + last)/2;
}
return 0;
}
Linear Search
Linear search algorithm is easy to learn. It search one by one in the array or list.
it compares one by one .
code.....
#include<stdio.h>
int main(){
int a[5]={3,6,2,7,8},n=5,i=0,j=0,target=7,step=0;
for(i=0;i<n;i++){
if(a[i]==target){
step=1;
printf("Found at index : %d ",i);
break;
}
}
if(step==0){
printf("Not found");
}
return 0;
}
Thank You
Binary Search
Binary Search algorithm divides data in two parts left and right and search in the sorted data. Sorted data should be provided to this algorithm.
code....
// Binary searth algorithm.
#include<stdio.h>
int main(){
int a[5]={2,4,6,8,12},n=5,target=8,first=0,last=0,middle=0,step=0;
first = 0;
last = n-1;
middle = (first + last)/2;
while(last>=first){
step++;
if(a[middle] > target){
last = middle-1;
}
else if (a[middle] == target){
printf("Found at index : %d",middle);
break;
}
else{
first = middle+1;
}
middle = (first + last)/2;
}
return 0;
}
Linear Search
Linear search algorithm is easy to learn. It search one by one in the array or list.
it compares one by one .
code.....
#include<stdio.h>
int main(){
int a[5]={3,6,2,7,8},n=5,i=0,j=0,target=7,step=0;
for(i=0;i<n;i++){
if(a[i]==target){
step=1;
printf("Found at index : %d ",i);
break;
}
}
if(step==0){
printf("Not found");
}
return 0;
}
Thank You
Comments
Post a Comment