Linear Search: A Simple Search: Traverses Found Exhausted
Linear Search: A Simple Search: Traverses Found Exhausted
1 7 9 12 33 42 59 76 81 84 91 92 93 99
Look for 42
Binary Search – Recursive Version
int BSearch(int Array[], int low, int high, int x)
{
int mid;
if(low<=high)
{
mid= (low+high)/2;
if (Array[mid]== x) return mid;
else
if(Array[mid]>x) BSearch (Array, low, mid-1,x);
else BSearch(Array, mid+1, high,x);
}
return -999;
}
Binary Search – Iterative Version
int BSearch(int Array[], int low, int high, int x)
{
int mid;
while(low<=high)
{
mid= (low+high)/2;
if (Array[mid]== x) return mid;
else
if(Array[mid]>x) high = mid-1;
else low = mid+1;
}
return -999;
}
Complexity – Binary Search
n, if n 1
F ( n)
F (n 1) F (n 2), if n 2
Fibonacci Numbers
• Computing the nth Fibonacci number recursively:
o F(n) = F(n-1) + F(n-2)
int Fib(int n)
o F(0) = 0 {
o F(1) = 1 if (n <= 1)
return 1;
o Top-down approach else
return Fib(n - 1) + Fib(n - 2);
}
F(n)
F(n-1) + F(n-2)
F(n-1) + F(n-2)
n levels
Fib(5)
+
Fib(4) Fib(3)
+ +
1
2
3
A B C
Recursive Solution (n=3)
Recursive Solution (n=3)
Recursive Solution (n=3)
Recursive Solution (n=3)
Recursive Solution (n=3)
Recursive Solution (n=3)
Recursive Solution (n=3)
Recursive Solution (n=3)
Recursive Solution (n=3)
Recursive Solution (n=3)
Recursive Solution (n=3)
Recursive Solution (n=3)
Try this one!
1
2
3
4
A B C
1
2
3
4
5
A B C
1
2
3
4
5
6
A B C
Shortest number of moves??
Where's the maths in this game?