I have an algorithmic test about implementing of binary search that works in a maximum amount of time of 2 seconds.
First, I've implemented a recursive version of binary search, but it was taking almost 3.6 seconds to finish in some test cases. Then, I changed it to an iterative version, but it takes 2.6 seconds in the same test case. However, I think that using a while loop
is a reason why it takes a lot of time.
My question is: What do I need to improve to make it take a maximum 2 seconds?
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int iterBinarySearch(vector<int> A, int low, int high, int key) {
int mid;
while (low <= high) {
mid = low + ((high - low)/2);
if (key < A[mid]) {
high = mid -1;
} else if (key > A[mid]) {
low = mid +1;
} else {
return mid;
}
}
return -1;
}
int main() {
vector<int>dict;
vector<int>keys;
int dictSize;
cin >> dictSize;
while (dictSize--) {
int val;
cin >> val;
dict.push_back(val);
}
int keysSize;
cin >> keysSize;
while (keysSize--) {
int val;
cin >> val;
keys.push_back(val);
}
sort(dict.begin(), dict.end());
int size = (int)dict.size() -1;
for(int i = 0; i< keys.size(); ++i) {
if ((dict[0] > keys[i]) || (dict[size] < keys[i])) {
cout << "-1" << ' ';
} else {
int res = iterBinarySearch(dict, 0, size, keys[i]);
cout << res << ' ';
}
}
return 0;
}
Aucun commentaire:
Enregistrer un commentaire