Untitled
unknown
c_cpp
a year ago
2.1 kB
5
Indexable
#include <iostream> #include <vector> #include <algorithm> using namespace std; void stressTest(); int compare(const void* a, const void* b); int binarySearch(const vector<int>& arr, int x) { int left = 0, right = arr.size() - 1; while (left <= right) { int mid = left + (right - left) / 2; if (arr[mid] == x) return mid; if (arr[mid] < x) left = mid + 1; else right = mid - 1; } return -1; } int main() { srand(0); stressTest(); // vector<int> arr; // int n, x, num; // // cout << "Nhập số lượng phần tử trong danh sách: "; // cin >> n; // // cout << "Nhập các phần tử (đã sắp xếp) trong danh sách: "; // for (int i = 0; i < n; i++) { // cin >> num; // arr.push_back(num); // } // // cout << "Nhập số cần tìm kiếm: "; // cin >> x; // // int result = binarySearch(arr, x); // // if (result != -1) // cout << "Số " << x << " được tìm thấy tại vị trí " << result << "." << endl; // else // cout << "Không tìm thấy số " << x << " trong danh sách." << endl; return 0; } void stressTest() { vector<int> arr; int n, x, num; n = rand() % 10; for (int i(0); i < n; i++) { int temp = -10 + rand() % 100; arr.push_back(temp); } qsort(&arr[0], arr.size(), sizeof(int), compare); cout << "Nhập số cần tìm kiếm: "; cin >> x; int result = binarySearch(arr, x); if (result != -1) cout << "Số " << x << " được tìm thấy tại vị trí " << result << "." << endl; else cout << "Không tìm thấy số " << x << " trong danh sách." << endl; for (auto num : arr) { cout << num << " "; } } int compare(const void* a, const void* b) { const int* x = (int*) a; const int* y = (int*) b; if (*x > *y) return 1; else if (*x < *y) return -1; return 0; }
Editor is loading...
Leave a Comment