Binary Search and common implementations (C++ and Python)

Binary Search and common implementations (C++ and Python)

Binary search is an algorithm for finding a specific element in an ordered array. It eliminates half of the elements by comparing the target value with the middle element of the array. If the target value is less than the middle element, the search continues in the left half of the array; if the target value is greater than the middle element, the search continues in the right half of the array; if the target value is equal to the middle element, the target value is found. Repeat this process until the target value is found or it is determined that the target value does not exist in the array. Binary search usually requires that the array to be searched is ordered. Compared with linear search, binary search is more efficient.

The premise of binary search is that the data is in order, and the specific implementation methods are: recursive implementation and iterative implementation. Applied to binary search, the recursive implementation gradually narrows the search range until the target element is found or the search range is empty. The iterative implementation uses a loop to update the search range until the target element is found or the search range is empty.

Here's an explanation of recursion and iteration:

recursion:

Recursion is a method of solving a problem by breaking it into smaller sub-problems. In recursion, a function calls itself to solve subproblems of the same type until the base case is reached (also called the recursion termination condition), and then the solutions to all subproblems are combined to get the final result. The key to recursion is to find the recursive termination condition and the process of the recursive call.

A key concept of recursive algorithms is "self-similarity", that is, the solution to a problem can be obtained by solving one or more smaller, similar sub-problems.

Iterate:

Iteration is a method of repeatedly performing a series of operations through a loop until a desired result is achieved. In iteration, the solution to a problem is broken down into a series of ordered steps, each step changing the state of the problem until a goal state or condition is reached. Iteration is usually implemented using loop structures (such as for, while loops).

Binary Search is an efficient search algorithm that can quickly locate the target value in an ordered array or ordered list. The following two common implementation methods are introduced below:

Binary search recursive implementation

1. Determine the low end (also called the left boundary) and the high end (right boundary) of the search range, which are initially the first element and the last element of the array.

2. Calculate the index mid of the middle element: mid = low + (high - low) / 2.

3. If the middle element is equal to the target value, return that index.

4. If the middle element is greater than the target value, continue searching in the left half: recursively call the binary search function and update the right boundary of the search range to mid - 1.

5. If the middle element is less than the target value, continue searching in the right half: recursively call the binary search function and update the left boundary of the search range to mid + 1.

6. If the left boundary is greater than the right boundary, it means that the target value is not found and -1 is returned.

Binary search iterative implementation

1. Determine the low end and high end of the search range, which are initially the first element and the last element of the array.

2. The loop termination condition is that the left boundary is less than or equal to the right boundary.

3. In the loop, calculate the index mid of the middle element: mid = low + (high - low) / 2.

4. If the middle element is equal to the target value, return that index.

5. If the middle element is greater than the target value, update the right boundary of the search range to mid - 1.

6. If the middle element is smaller than the target value, update the left boundary of the search range to mid + 1.

7. If the left boundary is greater than the right boundary at the end of the loop, it means that the target value is not found and -1 is returned.

The above two implementation methods are based on ordered arrays or ordered lists for searching, and the target value is quickly located by continuously narrowing the search scope. Recursive implementation uses recursive function calls to implement the search process, while iterative implementation uses loops to perform iterative search. The time complexity of both methods is O(log n).

The following are code examples of binary search in C++ and Python that implement recursive algorithms and iterative algorithms.

★Binary search C++ recursive algorithm implementation:

#include <iostream>
using namespace std;

int binarySearchRecursive(int arr[], int low, int high, int target) {
    if (low > high) {
        return -1; // 没有找到目标值,返回-1
    }
    
    int mid = low + (high - low) / 2;
    
    if (arr[mid] == target) {
        return mid; // 找到目标值,返回索引
    } else if (arr[mid] > target) {
        return binarySearchRecursive(arr, low, mid - 1, target); // 在左半部分继续查找
    } else {
        return binarySearchRecursive(arr, mid + 1, high, target); // 在右半部分继续查找
    }
}

int main() {
    int arr[] =  {1, 3, 5, 7, 9, 11};
    int n = sizeof(arr) / sizeof(arr[0]);
    int target = 3; // 
    
    int result = binarySearchRecursive(arr, 0, n - 1, target);
    
    if (result == -1) {
        cout << "Target not found" << endl;
    } else {
        cout << "Target found at index: " << result << endl;
    }
    
    return 0;
}

Tip: In C++, sizeof(arr) / sizeof(arr[0]) can get the length of a one-dimensional array.

★Python recursive algorithm implementation

def binarySearchRecursive(arr, low, high, target):
    if low > high:
        return -1 # 没有找到目标值,返回-1
    
    mid = low + (high - low) // 2
    
    if arr[mid] == target:
        return mid # 找到目标值,返回索引
    elif arr[mid] > target:
        return binarySearchRecursive(arr, low, mid - 1, target) # 在左半部分继续查找
    else:
        return binarySearchRecursive(arr, mid + 1, high, target) # 在右半部分继续查找

arr = [1, 3, 5, 7, 9, 11]
target = 3

result = binarySearchRecursive(arr, 0, len(arr) - 1, target)

if result == -1:
    print("Target not found")
else:
print("Target found at index:", result)

★C++ iterative algorithm implementation:

#include <iostream>
using namespace std;

int binarySearchIterative(int arr[], int low, int high, int target) {
    while (low <= high) {
        int mid = low + (high - low) / 2;
        
        if (arr[mid] == target) {
            return mid; // 找到目标值,返回索引
        } else if (arr[mid] < target) {
            low = mid + 1; // 在右半部分继续查找
        } else {
            high = mid - 1; // 在左半部分继续查找
        }
    }
    
    return -1; // 没有找到目标值,返回-1
}

int main() {
    int arr[] = {1, 3, 5, 7, 9, 11};
    int n = sizeof(arr) / sizeof(arr[0]);
    int target = 3;
    
    int result = binarySearchIterative(arr, 0, n - 1, target);
    
    if (result == -1) {
        cout << "Target not found" << endl;
    } else {
        cout << "Target found at index: " << result << endl;
    }
    
    return 0;
}

★Python iterative algorithm implementation:

def binarySearchIterative(arr, low, high, target):
    while low <= high:
        mid = low + (high - low) // 2
        
        if arr[mid] == target:
            return mid # 找到目标值,返回索引
        elif arr[mid] < target:
            low = mid + 1 # 在右半部分继续查找
        else:
            high = mid - 1 # 在左半部分继续查找

    return -1 # 没有找到目标值,返回-1

arr = [1, 3, 5, 7, 9, 11]
target = 3

result = binarySearchIterative(arr, 0, len(arr) - 1, target)

if result == -1:
    print("Target not found")
else:
    print("Target found at index:", result)

The above code examples demonstrate the use of C++ and Python languages ​​to implement binary search of recursive algorithms and iterative algorithms respectively. The core ideas are both binary search template algorithms. The difference is the implementation method, but the principles of both are the same.

Guess you like

Origin blog.csdn.net/cnds123/article/details/132420471