Skip to content

Commit 1277d83

Browse files
authored
Merge pull request #48 from Vivek13121/main
Implement Fibonacci search algorithm
2 parents 297f72a + b63ff27 commit 1277d83

2 files changed

Lines changed: 66 additions & 0 deletions

File tree

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
#include <bits/stdc++.h>
2+
using namespace std;
3+
4+
int eggDrop(int eggs, int floors) {
5+
vector<int> dp(floors + 1, 0), prev(floors + 1, 0);
6+
7+
for (int e = 1; e <= eggs; e++) {
8+
for (int f = 1; f <= floors; f++) {
9+
if (e == 1) {
10+
dp[f] = f;
11+
} else {
12+
dp[f] = INT_MAX;
13+
for (int k = 1; k <= f; k++) {
14+
int res = 1 + max(prev[k - 1], dp[f - k]);
15+
dp[f] = min(dp[f], res);
16+
}
17+
}
18+
}
19+
prev = dp;
20+
}
21+
return dp[floors];
22+
}
23+
24+
int main() {
25+
int eggs = 2, floors = 10;
26+
cout << "Minimum number of trials in worst case: "
27+
<< eggDrop(eggs, floors) << endl;
28+
return 0;
29+
}
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
def fibonacci_search(arr, x):
2+
n = len(arr)
3+
f2 = 0
4+
f1 = 1
5+
f = f1 + f2
6+
7+
while f < n:
8+
f2 = f1
9+
f1 = f
10+
f = f1 + f2
11+
12+
offset = -1
13+
14+
while f > 1:
15+
i = min(offset + f2, n - 1)
16+
17+
if arr[i] < x:
18+
f = f1
19+
f1 = f2
20+
f2 = f - f1
21+
offset = i
22+
elif arr[i] > x:
23+
f = f2
24+
f1 = f1 - f2
25+
f2 = f - f1
26+
else:
27+
return i
28+
29+
if f1 and offset + 1 < n and arr[offset + 1] == x:
30+
return offset + 1
31+
32+
return -1
33+
34+
arr = [10, 22, 35, 40, 45, 50, 80, 82, 85, 90, 100]
35+
target = 85
36+
result = fibonacci_search(arr, target)
37+
print(f"Target {target} found at index: {result}")

0 commit comments

Comments
 (0)