Showing posts with label linear binary search searching algorithms. Show all posts
Showing posts with label linear binary search searching algorithms. Show all posts

Jul 31, 2020

Linear Search - Binary Search - Searching Algorithms - Coding Winds

LINEAR SEARCH AND BINARY SEARCH ALGORITHM

Hey guys, we are back with another blog and today we are going talk about linear and binary searching in java. So primarily let us see what is searching, searching basically refers to finding out a specific element from an array. Linear search is a searching algorithm that runs to find out the element from the array by checking each and every array element one by one. Whereas, binary search divides the array into two halves and then searches for the element. So let's look further at the differences and the algorithm of the two.


LINEAR SEARCH


In linear search the element to be found out is searched for, throughout the array and the as soon as the element is found the loop breaks. So the time complexity of this algorithm is O(n2). Now let's see how to implement this in code.

 

public class LinearSearch {

     static String linearSearch(int ar[],int num) {

        

         result="";

         for(int i=0; i<ar.length; i++) {

     if(num==ar[i]) {

     result= "Number found at index "+i;

     break;

    

     else

     result= "Number not found";

    

     return result;

    

 

     public static void main(String[] args) {

        

         int ar[] = {12, 45, 9,23, 6,11};

         int min=ar[0];

        int num = 23;

       out.println(ar,num));

}

}

 

BINARY SEARCH


Binary search is possible in a sorted array, since in this the array is divided into two halves. And then the element to be searched (or key value),

Let's us see this in code

     import java.util.*;

 

public class BinarySearch {

 

     public static void binarySearch(int arr[], int first, int last, int key){

         int mid = (first + last)/2;

         while( first <= last ){

         if ( arr[mid] < key ){

         first = mid + 1;

         else if ( arr[mid] == key ){

         out.println("Element is found at index: " + mid);

         break;

         else{

         last = mid - 1;

        

         mid = (first + last)/2;

        

         if ( first > last ){

         out.println("Element is not found!");

        

        

         public static void main(String args[]){

              int arr[] = {10,20,30,40,50};

         int num = 40;

         int last=arr.length-1;

         arr,0,last,num);

        

        

          

 

OUTPUT: Element is found at index: 3

 

Note that, for binary search an array needs to be sorted, else we cannot divide the array into two halves and hence this algo cannot be executed.