Todays Program:

Binary Search:

Binary search is an efficient algorithm for finding an item from a sorted list of items. It works by repeatedly dividing in half the portion of the list that could contain the item, until you’ve narrowed down the possible locations to just one.

Why it is called binary search?

It is called binary because it splits the array into two halves as part of the algorithm.

Program:

package demo;

public class Binarysearch {

public static void main(String[] args) {
    // TODO Auto-generated method stub
     int []bookarr= {0,1,2,3,4,5,6,7};
      int firstpage=0;
      int lastpage=bookarr.length;
      int midpage=(firstpage+lastpage)/2;
      int tofind=6;
      boolean found=false;

      while(firstpage<lastpage) {
       if(bookarr[midpage]<tofind) {
        firstpage=midpage+1;
          }
       else if(bookarr[midpage]==tofind) {
        System.out.println("the number is found on arrindex "+bookarr[midpage]);
        found=true;
        break;
       }
       else {
        lastpage=midpage-1;
       }
       midpage=(firstpage+lastpage)/2;
      }
      if(found==false) {
       System.out.println("not found");
      }
     }



}

Output:

the number is found on arrindex 6

Program for finding odd number:

package demo;

import java.util.Arrays;

public class oddindexsaving {

public static void main(String[] args) {
    // TODO Auto-generated method stub
      int[]ar= {10,245,30,460,50};
      int oddsize=ar.length/2;
      int []oddar=new int[oddsize];
      int j=0;
    for(int i=1;i<ar.length;i=i+2) {
        oddar[j]=ar[i];
        j++;

    }
    System.out.println(Arrays.toString(oddar));
}

}

Output:

[245, 460]

Program for finding method:

package demo;

import java.util.Arrays;

public class Method {

public static void main(String[] args) {
    // TODO Auto-generated method stub
    int[]ar1= {10,20,30,40};
    int[]ar2= {5,10};
    int bigIndex=ar1.length>ar2.length?ar1.length:ar2.length; //terinary operator
    int[]ar3=new int[bigIndex];
    for(int i=0;i<bigIndex;i++) {
        if(i<ar1.length) {
            ar3[i]=ar1[i];

        }
        if(i<ar2.length) {
            ar3[i]=ar3[i]+ar2[i];
        }
    }
    System.out.println(Arrays.toString(ar3));
}

}

Output:

[15, 30, 30, 40]

Leave a comment

Design a site like this with WordPress.com
Get started