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.
|
* @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 fibonacci_search(const std::vector<int> &arr, int value){
|
||||||
int last = 0, current = 1, offset = -1, index;
|
// initialize last and current members of Fibonacci sequence
|
||||||
int length = arr.size();
|
int last = 0, current = 1;
|
||||||
|
int length = arr.size(); // array size
|
||||||
|
// next member of Fibonacci sequence which is "last" + "current"
|
||||||
int next = last + current;
|
int next = last + current;
|
||||||
|
|
||||||
|
// "next" will store the smallest Fibonacci number greater or equal to "length"
|
||||||
while(next < length){
|
while(next < length){
|
||||||
last = current;
|
last = current;
|
||||||
current = next;
|
current = next;
|
||||||
next = last + current;
|
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){
|
while(next > 1){
|
||||||
|
// check if "last" is valid location
|
||||||
index = std::min(offset + last, length-1);
|
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){
|
if(arr[index] < value){
|
||||||
next = current;
|
next = current;
|
||||||
current = last;
|
current = last;
|
||||||
last = next - current;
|
last = next - current;
|
||||||
offset = index;
|
offset = index;
|
||||||
|
// if value is less than the value at "index", eliminate the subarray after index+1
|
||||||
} else if(arr[index] > value){
|
} else if(arr[index] > value){
|
||||||
next = last;
|
next = last;
|
||||||
current = current - last;
|
current = current - last;
|
||||||
last = next - current;
|
last = next - current;
|
||||||
|
// element is found
|
||||||
} else {
|
} else {
|
||||||
return index;
|
return index;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// comparing the last element
|
||||||
if(current && !arr.empty() && arr[offset+1] == value){
|
if(current && !arr.empty() && arr[offset+1] == value){
|
||||||
return offset+1;
|
return offset+1;
|
||||||
}
|
}
|
||||||
|
// value was not found, return -1
|
||||||
return -1;
|
return -1;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Loading…
Reference in New Issue
Block a user