Java: Big-O-Binary Search Algorithm

Level : Beginner
Mentor: Amit Kumar Ghosh
Type : GuidedLab
Points : 10
Duration : 00:15:00

Lab Details

Difficulty Level: MEDIUM

Problem Statement:

Analyse the time complexity of the Binary Search method in the given Java code. The method is designed to find an element ‘x’ in a sorted array ‘arr’ using a binary search approach.

Describe the Big-O notation that best represents the time complexity of this method.

public class BinarySearch {

    public static int binarySearch(int[] arr, int left, int right, int x) {

        while (left <= right) {

            int mid = left + (right - left) / 2;

            // Check if x is present at mid

            if (arr[mid] == x)

                return mid;

            // If x is greater, ignore left half

            if (arr[mid] < x)

                left = mid + 1;

            // If x is smaller, ignore right half

            else

                right = mid - 1;

        }

        // element not present in array

        return -1;

    }

    public static void main(String[] args) {

        int arr[] = { 2, 5, 7, 8, 12, 16 };

        int x = 8;

        int result = binarySearch(arr, 0, arr.length - 1, x);

        if (result == -1)

            System.out.println("Element not present in array");

        else

            System.out.println("Element found at index " + result);

    }

}

Self-paced Membership
  • 24+ Video Courses
  • 825+ Hands-On Labs
  • 400+ Quick Notes
  • 125+ Skill Tests
  • 10+ Interview Q&A Courses
  • 10+ Real-world Projects
  • Career Coaching Sessions
  • Email Support
Upto 60% OFF
Know More
Still have some questions? Let's discuss.
CONTACT US
Accept cookies & close this