DEV Community

Bhupesh Chandra Joshi
Bhupesh Chandra Joshi

Posted on

Why 100 lines of code be better than 2?

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
}



Enter fullscreen mode Exit fullscreen mode

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.

Enter fullscreen mode Exit fullscreen mode

Top comments (0)