Lab 3
Lab 3
OF
ALGORITHMS
LAB3
AGENDA
• Brute force vs Divide and conquer
• Linear Search vs Binary search
• Selection sort vs Merge sort
Cons-
•Fairly inefficient, in both time complexity
and space
•Not very suitable in real world
applications.
}
high = mid - 1;
Time Complexity:
// If we reach here, then element was not present
return -1;
O(log N)
} Theory of algorithms Lab3
BINARY SEARCH(WITH RECURSION)
#include <iostream> int main() {
using namespace std; int arr[] = {1, 3, 5, 7, 9, 11, 13, 15};
int size = sizeof(arr) / sizeof(arr[0]);
int binarySearch(int arr[], int low, int high, int target) { int target = 7;
// Base case: target not found int result = binarySearch(arr, 0, size - 1,
if (low > high) target);
return -1;
if (result != -1)
int mid = (low + high) / 2; cout << "Element found at index " << result
<< endl;
// Check if the middle element is the target else
if (arr[mid] == target) cout << "Element not found" << endl;
return mid; return 0;
Outp
// If target is smaller than mid, search in the left half }
else if (arr[mid] > target)
return binarySearch(arr, low, mid - 1, target); ut:
// If target is larger than mid, search in the right half
else
return binarySearch(arr, mid + 1, high, target);
}