Coding Example: Searching in a book
You know that book page numbers are sorted,
int book[100];
for(int i = 0; i < 100; i++) {
book[i] = i + 1; // page numbers 1 to 100
}
Method 1: Linear Search
for(int i=0;i<100;i++){
if(book[i]==key)
page=arr[i]
}
You know that we are traversing the each element of an array, so the time duration will decide how well the program construction. The line of code doesn't fabricate the desired fast program which every device requires, time is considered money nowdays.
int start=0;
int end=100;
int mid;
while(start<=end){
mid=start+end/2;
if(book[mid]==key){
page=book[mid];
break;
} else if(book[mid]<key){
// mid k agane page se book padni hai
start=mid+1;
}else{
end=mid-1;
}
}
Here the particular block will run, which case will be true that part will be executed.
Top comments (0)