diff --git a/search/fibonacci_search.cpp b/search/fibonacci_search.cpp index dd1b06f11..be181a47d 100644 --- a/search/fibonacci_search.cpp +++ b/search/fibonacci_search.cpp @@ -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 &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; }