mirror of
https://hub.njuu.cf/TheAlgorithms/C-Plus-Plus.git
synced 2023-10-11 13:05:55 +08:00
comments added
This commit is contained in:
parent
644524337a
commit
58099884dd
@ -21,34 +21,48 @@
|
||||
* @returns if the array contains the value, returns an index of the element. otherwise -1.
|
||||
*/
|
||||
int fibonacci_search(const std::vector<int> &arr, int value){
|
||||
int last = 0, current = 1, offset = -1, index;
|
||||
int length = arr.size();
|
||||
int next = last + current;
|
||||
// initialize last and current members of Fibonacci sequence
|
||||
int last = 0, current = 1;
|
||||
int length = arr.size(); // array size
|
||||
// next member of Fibonacci sequence which is "last" + "current"
|
||||
int next = last + current;
|
||||
|
||||
// "next" will store the smallest Fibonacci number greater or equal to "length"
|
||||
while(next < length){
|
||||
last = current;
|
||||
current = next;
|
||||
next = last + current;
|
||||
}
|
||||
|
||||
// "offset" is the end of eliminated range from front
|
||||
int offset = -1, index;
|
||||
// while loop until there are elements left to consider.
|
||||
// when "next" becomes 1, last is equal to 0, so search is done,
|
||||
// because arr[offset] will already be eliminated
|
||||
while(next > 1){
|
||||
// check if "last" is valid location
|
||||
index = std::min(offset + last, length-1);
|
||||
// if value is greater than the value at "index", eliminate the subarray from offset to index
|
||||
if(arr[index] < value){
|
||||
next = current;
|
||||
current = last;
|
||||
last = next - current;
|
||||
offset = index;
|
||||
// if value is less than the value at "index", eliminate the subarray after index+1
|
||||
} else if(arr[index] > value){
|
||||
next = last;
|
||||
current = current - last;
|
||||
last = next - current;
|
||||
// element is found
|
||||
} else {
|
||||
return index;
|
||||
}
|
||||
}
|
||||
// comparing the last element
|
||||
if(current && !arr.empty() && arr[offset+1] == value){
|
||||
return offset+1;
|
||||
}
|
||||
// value was not found, return -1
|
||||
return -1;
|
||||
}
|
||||
|
||||
|
Loading…
Reference in New Issue
Block a user