Fibonacci search algorithm
More...
#include <iostream>
#include <vector>
#include <cassert>
#include <cstdlib>
#include <algorithm>
|
| int | fibonacci_search (const std::vector< int > &arr, int value) |
| | using fibonacci search algorithm finds an index of a given element in a sorted array More...
|
| |
| bool | no_occurence_tests () |
| | random tests for checking performance when an array doesn't contain an element More...
|
| |
| bool | random_tests () |
| | random tests which cover cases when we have one, multiple or zero occurences of the value we're looking for More...
|
| |
| int | main () |
| |
◆ fibonacci_search()
| int fibonacci_search |
( |
const std::vector< int > & |
arr, |
|
|
int |
value |
|
) |
| |
using fibonacci search algorithm finds an index of a given element in a sorted array
- Parameters
-
| arr | sorted array |
| value | value that we're looking for |
- Returns
- if the array contains the value, returns an index of the element. otherwise -1.
25 int last = 0, current = 1;
26 int length = arr.
size();
28 int next = last + current;
34 next = last + current;
38 int offset = -1, index;
44 index =
std::min(offset + last, length-1);
46 if(arr[index] < value){
49 last =
next - current;
52 }
else if(arr[index] > value){
54 current = current - last;
55 last =
next - current;
62 if(current && !arr.
empty() && arr[offset+1] == value){
◆ main()
Main Function testing the algorithm
bool random_tests()
random tests which cover cases when we have one, multiple or zero occurences of the value we're looki...
Definition: fibonacci_search.cpp:96
bool no_occurence_tests()
random tests for checking performance when an array doesn't contain an element
Definition: fibonacci_search.cpp:72
◆ no_occurence_tests()
| bool no_occurence_tests |
( |
| ) |
|
random tests for checking performance when an array doesn't contain an element
74 int rand_num, rand_value, index, num_tests = 1000;
78 for(
int i = 0; i < 100; i++){
88 passed = passed && (index == -1);
int fibonacci_search(const std::vector< int > &arr, int value)
using fibonacci search algorithm finds an index of a given element in a sorted array
Definition: fibonacci_search.cpp:23
◆ random_tests()
random tests which cover cases when we have one, multiple or zero occurences of the value we're looking for
98 int rand_num, rand_value, index, real_value, num_tests = 10000;
102 for(
int i = 0; i < 100; i++){
110 real_value = arr[index];
111 passed = passed && (real_value == rand_value);