Linear and Binary search methods in java


public class Search_methods {
/**
        * @author Alihan98ersoy
        * 01.07.2017(month,day,year)
        * Contents:
        * Linear Search
        * Binary Search
*/
       //Linear Search
       //Searching one by one

       public int LinearSearch(int[]list,int target){
             for(int i=0;i<list.length;i++){
                    if(list[i]==target){return i; }
             }
             return -1;//not found case
       }

       //Binary Search
       //requires sorted array

       public int BinarySearch(int[]list,int target){
             if(isSorted(list)==false){Selectionsort(list);}//if is not sorted sorting it
             int high=list.length-1,low=0;
             int mid=(high+low)/2;
             while(mid!=high){ mid=(high+low)/2;
                    if(list[mid]==target){return mid;}
                    if(target<list[mid]){high=mid-1;}
                    else{low=mid+1;}
             } return -1; }
       //Other methods
       public boolean isSorted(int[]list){
             for(int i=0;i<list.length-1;i++){
                    if(list[i]>list[i+1]){return false;}
             }
             return true;
       }
       //Selection sort
       //Find the smallest number in second for replacing it with first for integer i.
             public void Selectionsort(int[]list){
                   
                    for(int i=0;i<list.length;i++){
                          int indexofsmallestnumber=i;
                         
                          for(int j=i+1;j<list.length;j++){
          if(list[j]<list[indexofsmallestnumber]){indexofsmallestnumber=j;}     
                          }
                          int basket=list[indexofsmallestnumber];//basket for replace
                          list[indexofsmallestnumber]=list[i];
                          list[i]=basket;
                    }
             }
      
       public static void main(String[] args) {
             Search_methods a=new Search_methods();
             int[]array={3,2,1,5,6,9,8,10,4,7};
 System.out.println("Where is target in array(LinearSearch): "+a.LinearSearch(array,9));
    //if -1 means not found

 System.out.println("Where is target in array(BinarySearch): "+a.BinarySearch(array,5));
//if -1 means not found and don't forget binary search sorting array answer will be target-1!!!! 
}
      
      
}

                                            And
                          http://www.java67.com/2016/10/binary-search-using-recursion-in-java.html


Yorumlar

Bu blogdaki popüler yayınlar

Engelsizkitap

Sort methods in java