Share 704. binary search leetcode c++,

anhthu398

New member
#nhị phân-tìm kiếm, #LeetCode, #c ++, #Programming ## 704. Tìm kiếm nhị phân trong C ++

Tìm kiếm nhị phân là một thuật toán phân chia và chinh phục có thể được sử dụng để tìm vị trí của giá trị mục tiêu trong một mảng được sắp xếp.Nó hoạt động bằng cách liên tục chia không gian tìm kiếm làm đôi cho đến khi tìm thấy giá trị đích hoặc xác định rằng giá trị đích không nằm trong mảng.

Sau đây là việc triển khai tìm kiếm nhị phân trong C ++:

`` `C ++
#include <Istream>

sử dụng không gian tên STD;

int nhị phân nghiên cứu (int mảng [], int n, int target) {
int low = 0;
int cao = n - 1;

while (thấp <= cao) {
int mid = (thấp + cao) / 2;

if (mảng [mid] == target) {
trở lại giữa;
} if if (mảng [mid] <target) {
Thấp = Mid + 1;
} khác {
cao = giữa - 1;
}
}

trả lại -1;
}

int main () {
int mảng [] = {1, 3, 5, 7, 9};
int n = sizeof (mảng) / sizeof (mảng [0]);
Target int = 5;

int result = BinarySearch (ARR, N, Target);

if (result == -1) {
cout << "mục tiêu không tìm thấy" << endl;
} khác {
cout << "Mục tiêu được tìm thấy tại chỉ mục" << result << endl;
}

trả lại 0;
}
`` `

## Độ phức tạp thời gian

Độ phức tạp của thời gian của tìm kiếm nhị phân là O (log n), trong đó n là kích thước của mảng.

## Độ phức tạp không gian

Độ phức tạp không gian của tìm kiếm nhị phân là O (1).

## hashtags

* Tìm kiếm nhị phân
* LeetCode
* C ++
* Lập trình
* Thuật toán
=======================================
#binary-search, #LeetCode, #C++, #Programming ## 704. Binary Search in C++

Binary search is a divide-and-conquer algorithm that can be used to find the position of a target value in a sorted array. It works by repeatedly dividing the search space in half until the target value is found or it is determined that the target value is not in the array.

The following is an implementation of binary search in C++:

```c++
#include <iostream>

using namespace std;

int binarySearch(int arr[], int n, int target) {
int low = 0;
int high = n - 1;

while (low <= high) {
int mid = (low + high) / 2;

if (arr[mid] == target) {
return mid;
} else if (arr[mid] < target) {
low = mid + 1;
} else {
high = mid - 1;
}
}

return -1;
}

int main() {
int arr[] = {1, 3, 5, 7, 9};
int n = sizeof(arr) / sizeof(arr[0]);
int target = 5;

int result = binarySearch(arr, n, target);

if (result == -1) {
cout << "Target not found" << endl;
} else {
cout << "Target found at index " << result << endl;
}

return 0;
}
```

## Time Complexity

The time complexity of binary search is O(log n), where n is the size of the array.

## Space Complexity

The space complexity of binary search is O(1).

## Hashtags

* binary search
* leetcode
* c++
* programming
* algorithms
 
Join Telegram ToolsKiemTrieuDoGroup
Back
Top