Untitled

mail@pastecode.io avatar
unknown
plain_text
a month ago
721 B
1
Indexable
Never
#include <iostream>
using namespace std;

int binary_search(int arr[], int n, int x) {
  int left = 0;
  int right = n - 1;

  while (left <= right) {
    int mid = (left + right) / 2;

    if (arr[mid] == x) {
      return mid;
    } else if (arr[mid] < x) {
      left = mid + 1;
    } else {
      right = mid - 1;
    }
  }

  return -1;
}

int main() {
  int arr[] = {1, 2, 3, 4, 5, 6};
  int n = sizeof(arr) / sizeof(arr[0]);
  int x = 4;

  int result = binary_search(arr, n, x);

  if (result == -1) {
    cout << "Khong tim thay " << x << " trong mang." << endl;
  } else {
    cout << "Tim thay " << x << " tai vi tri " << result << " trong mang." << endl;
  }

  return 0;
}
Leave a Comment