Binary Search
Binary Search
Searching
Searching refers to the process of finding a specific element in a dataset. The goal is to
locate the position of the desired element (if it exists) in the data structure.
Common Searching Techniques:
1. Linear Search:
2. Binary Search:
a. Requires the dataset to be sorted.
3. Hashing:
Sorting
Sorting is the process of arranging elements in a specific order (e.g., ascending or
descending). It is often a prerequisite for efficient searching (e.g., binary search).
Common Sorting Algorithms:
1. Bubble Sort:
2. Selection Sort:
a. Repeatedly selects the smallest (or largest) element and places it in the
3. Insertion Sort:
4. Merge Sort:
5. Quick Sort:
6. Heap Sort:
Linear Search
Linear Search is a straightforward searching algorithm that checks every element in the
array sequentially until the desired element is found or the end of the array is reached.
Algorithm for Linear Search:
1. Start from the first element of the array.
2. Compare the current element with the target value.
3. If the target is found, return its index.
4. If not, move to the next element.
5. Repeat steps 2-4 until the array ends.
6. If the target is not found, return -1 or indicate failure.
Java Code for Linear Search:
public class LinearSearch {
public static int linearSearch(int[] array, int target) {
for (int i = 0; i < array.length; i++) {
if (array[i] == target) {
return i; // Return the index where the target is found
}
}
return -1; // Return -1 if the target is not found
}
public static void main(String[] args) {
int[] arr = {10, 20, 30, 40, 50};
int target = 30;
int result = linearSearch(arr, target);
if (result != -1) {
System.out.println("Element found at index: " + result);
} else {
System.out.println("Element not found.");
}
}
}
Binary Search
Binary Search is a more efficient searching algorithm that works on sorted arrays. It
repeatedly divides the array into halves to find the target.
Algorithm for Binary Search:
1. Start with two pointers: low (beginning of the array) and high (end of the array).
2. Calculate the middle index: mid = (low + high) / 2.
3. Compare the middle element with the target:
a. If they are equal, return the mid index.
b. If the target is smaller, search in the left half (high = mid - 1).
c. If the target is larger, search in the right half (low = mid + 1).
4. Repeat steps 2-3 until low > high.
5. If the target is not found, return -1.
Java Code for Binary Search:
public class BinarySearch {
public static int binarySearch(int[] array, int target) {
int low = 0;
int high = array.length - 1;
while (low <= high) {
int mid = low + (high - low) / 2; // Avoids overflow
if (array[mid] == target) {
return mid; // Return the index where the target is found
} else if (array[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 target is not found
}
Comparison: