Project Solution: How to Implement Binary Search

Rumman Ansari   Software Engineer   2024-07-13 05:22:54   92  Share
Subject Syllabus DetailsSubject Details
☰ TContent
☰Fullscreen

Table of Content:

  • Introduction to Binary Search

    • Binary search is an algorithm that finds the position of a target value within a sorted array. It compares the target value to the middle element of the array. If they are not equal, the half in which the target cannot lie is eliminated, and the search continues on the remaining half until the target value is found or the array is empty.
  • Setting Up the Environment

  • Creating the Binary Search Class

  • 
    import java.util.Arrays;
    import java.util.Scanner;
    
    public class BinarySearch {
    
        private int[] data;
    
        public BinarySearch(int[] data) {
            this.data = Arrays.copyOf(data, data.length);
            Arrays.sort(this.data);
        }
    
        public int search(int target) {
            int left = 0;
            int right = data.length - 1;
    
            while (left <= right) {
                int mid = left + (right - left) / 2;
    
                if (data[mid] == target) {
                    return mid; // Element found, return its index
                } else if (data[mid] < target) {
                    left = mid + 1; // Search in the right half
                } else {
                    right = mid - 1; // Search in the left half
                }
            }
    
            return -1; // Element not found
        }
    
        public static void main(String[] args) {
            int[] data = {2, 5, 7, 10, 15, 20, 29, 30, 46, 50};
            BinarySearch binarySearch = new BinarySearch(data);
    
            Scanner scanner = new Scanner(System.in);
            System.out.print("Enter the element to search for: ");
            int element = scanner.nextInt();
    
            int position = binarySearch.search(element);
    
            if (position != -1) {
                System.out.println("Element " + element + " found at position " + position + ".");
            } else {
                System.out.println("Search element not found.");
            }
    
            scanner.close();
        }
    }
    
    
    1. Documenting the Code

      • Add comments to your code explaining the purpose of each variable and method.
      • Create a README file to explain how to compile and run your program.
    2. Conclusion

      • Reflect on the binary search algorithm and its efficiency.
      • Consider edge cases, such as searching for an element not in the list or handling an empty list.
      • Explore how binary search can be extended or optimized further.

    Evaluation Criteria:

    • Correct implementation of the binary search algorithm.
    • Proper handling of user input.
    • Clear and comprehensive documentation.
    • Successful execution and testing of the program.

    Additional Resources: