Deletion in Arrays
Insertion in Arrays
Introduction to Arrays
Traversal in Arrays
Searching is one of the most fundamental operations performed on arrays. It involves locating the position of a specific element within the array. Understanding and efficiently implementing search operations is crucial for many programming tasks. This guide will explore different searching techniques, their applications, and provide practical examples.
Searching is essential for:
.png)
Linear search is straightforward and works on both sorted and unsorted arrays. It is easy to implement but can be inefficient for large datasets.
#include <iostream>
using namespace std;
int linearSearch(int arr[], int n, int x) {
    // Step 1: Start
    // Step 2: Iterate
    for (int i = 0; i < n; i++) {
        // Step 3: Compare
        if (arr[i] == x) {
            // Step 4: Return
            return i;
        }
    }
    // Step 4: Return
    return -1;
    // Step 5: End
}
int main() {
    int arr[] = {10, 20, 30, 40, 50};
    int n = sizeof(arr) / sizeof(arr[0]);
    int x = 30;  // Element to search for
    int result = linearSearch(arr, n, x);
    if (result != -1) {
        cout << "Element found at index " << result << endl;
    } else {
        cout << "Element not found in the array" << endl;
    }
    return 0;
}
 
.png)
Binary search is efficient but requires the array to be sorted. It repeatedly divides the search interval in half and compares the target value with the middle element.
#include <iostream>
using namespace std;
int binarySearch(int arr[], int low, int high, int x) {
    while (low <= high) {
        // Step 3: Divide
        int mid = low + (high - low) / 2;
        // Step 4: Compare
        if (arr[mid] == x) {
            // If the element is present at the middle
            return mid;
        }
        if (arr[mid] < x) {
            // If the element is present in the right subarray
            low = mid + 1;
        } else {
            // If the element is present in the left subarray
            high = mid - 1;
        }
    }
    // Element is not present in the array
    return -1;
}
int main() {
    int arr[] = {10, 20, 30, 40, 50};
    int n = sizeof(arr) / sizeof(arr[0]);
    int x = 30;  // Element to search for
    int result = binarySearch(arr, 0, n - 1, x);
    if (result != -1) {
        cout << "Element found at index " << result << endl;
    } else {
        cout << "Element not found in the array" << endl;
    }
    return 0;
}
 
Searching in arrays is a fundamental operation in programming. Understanding and implementing efficient search techniques, like linear and binary search, can significantly improve the performance of your applications. This guide provides a comprehensive overview of these techniques, from basic concepts to practical implementation, ensuring you have the knowledge to handle array searching effectively.
