Q:

Linear Search vs Binary Search in java programming

0

The objective of this assignment is to implement a Linear Search Algorithm and a Binary Search Algorithm.

  1. Linear search or sequential search is an algorithm that will traverse the whole data structure in order to search for an element. In this assignment, we will see a linear search algorithm over an array. (See Slides)
  2. Binary search is said to be a logarithmic search or half-interval search, which is a very efficient algorithm in order to search an element from a sorted collection. (See Slides)

Implement the Algorithms using Java Language and Display the total number of comparisons made by each searching Algorithm.

 

COURSE : CIS 202 / assignment 1 / al yamama university 

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

linear search algorithm implementation:

public class Main
{
	public static void main(String[] args) {
	    
	    //linear search algorithm implementation
	    int []arr={45,2,3,22,78,14,25,65,3,12};
	    for(int i=0;i<10;i++)
	    {
	        if(arr[i]==65)
	        {
	            System.out.println("found after "+(i+1)+" times");
	        }
	    }
	    }
}

Total number of comparisons: 8

 

binary search algorithm implementation:

public class Main
{
	public static void main(String[] args) {
	    //binary search algorithm implementation
	    int []arr={45,2,3,22,78,14,25,65,3,12};
	    binarySearch(arr,65);
	}
public static int binarySearch(int[] arr, int target) {
    int left = 0;
    int right = arr.length - 1;
    int comparisons = 0;

    while (left <= right) {
        int mid = left + (right - left) / 2;
        comparisons++;

        if (arr[mid] == target) {
            System.out.println("Total number of comparisons: " + comparisons);
            return mid;
        } else if (arr[mid] < target) {
            left = mid + 1;
        } else {
            right = mid - 1;
        }
    }
    System.out.println("Total number of comparisons: " + comparisons);
    return -1;
}
}

Total number of comparisons: 4

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Similar questions


need a help?


find thousands of online teachers now