Physical Address

304 North Cardinal St.
Dorchester Center, MA 02124

A Complete Guide to Linear Search and Binary Search with Java Examples

Day 19: Searching Algorithms – Linear and Binary Search

Searching algorithms are essential in computer science, enabling us to find specific elements within data structures efficiently. In this post, we will explore two fundamental searching algorithms: Linear Search and Binary Search. We’ll discuss their explanations, implementations in Java, key differences, and example problems.

What is Linear Search?

Linear Search is the simplest searching algorithm. It works by sequentially checking each element in the array until the desired element is found or the end of the array is reached. This algorithm does not require the array to be sorted.

Implementation in Java

Here’s how you can implement Linear Search in Java:

javaCopy codepublic class LinearSearch {
    public static int linearSearch(int[] arr, int target) {
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] == target) {
                return i; // Return the index of the found element
            }
        }
        return -1; // Return -1 if the element is not found
    }

    public static void main(String[] args) {
        int[] arr = {5, 3, 8, 4, 2};
        int target = 4;
        int result = linearSearch(arr, target);
        if (result != -1) {
            System.out.println("Element found at index: " + result);
        } else {
            System.out.println("Element not found.");
        }
    }
}

What is Binary Search?

Binary Search is a more efficient searching algorithm that requires the array to be sorted. It works by repeatedly dividing the search interval in half. If the target value is less than the middle element, the search continues in the left half; if greater, it continues in the right half.

Implementation in Java

Here’s how you can implement Binary Search in Java:

javaCopy codepublic class BinarySearch {
    public static int binarySearch(int[] arr, int target) {
        int low = 0;
        int high = arr.length - 1;

        while (low <= high) {
            int mid = low + (high - low) / 2; // Calculate the middle index

            if (arr[mid] == target) {
                return mid; // Target found
            }
            if (arr[mid] < target) {
                low = mid + 1; // Search in the right half
            } else {
                high = mid - 1; // Search in the left half
            }
        }
        return -1; // Return -1 if the element is not found
    }

    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4, 5, 6, 7};
        int target = 4;
        int result = binarySearch(arr, target);
        if (result != -1) {
            System.out.println("Element found at index: " + result);
        } else {
            System.out.println("Element not found.");
        }
    }
}

Key Differences Between Linear Search and Binary Search

FeatureLinear SearchBinary Search
Array OrderUnsorted arrayRequires sorted array
Time ComplexityO(n)O(log n)
Space ComplexityO(1) (iterative version)O(1) (iterative version)
Use CaseSmall datasets or unsorted dataLarge sorted datasets

Example Problems

  1. Linear Search Example: Given an array of integers: {10, 15, 20, 25, 30} and a target value of 20, Linear Search will return the index 2.
  2. Binary Search Example: Given a sorted array: {1, 2, 3, 4, 5} and a target value of 3, Binary Search will return the index 2.

Conclusion

Linear Search and Binary Search are fundamental searching algorithms with distinct use cases. Linear Search is simple and works on unsorted data, while Binary Search is efficient and ideal for sorted datasets. Understanding both algorithms is crucial for effective data retrieval.

In our next post, we will explore Recursion and its importance in algorithms. Stay tuned!

Also see: The Z Blogs

my other Blog: The Z Blog ZB

Do share with your friends and family
The Z blogs
The Z blogs
Articles: 148

3 Comments

  1. I was wondering if you ever considered changing the structure of your blog? Its very well written; I love what youve got to say. But maybe you could a little more in the way of content so people could connect with it better. Youve got an awful lot of text for only having 1 or 2 images. Maybe you could space it out better?

  2. Thanks for sharing your ideas right here. The other element is that each time a problem arises with a computer motherboard, individuals should not consider the risk connected with repairing that themselves because if it is not done properly it can lead to irreparable damage to the full laptop. It is almost always safe just to approach a dealer of the laptop for that repair of motherboard. They have got technicians that have an knowledge in dealing with notebook motherboard problems and can get the right prognosis and undertake repairs.

  3. I might also like to convey that most of those that find themselves without the need of health insurance are usually students, self-employed and those that are not working. More than half with the uninsured are really under the age of Thirty-five. They do not sense they are requiring health insurance since they are young and also healthy. Their particular income is normally spent on real estate, food, as well as entertainment. Lots of people that do represent the working class either complete or part-time are not supplied insurance via their jobs so they get along without because of the rising valuation on health insurance in the usa. Thanks for the tips you discuss through this site.

Leave a Reply

Your email address will not be published. Required fields are marked *