Binary Search C
Binary Search C
h>
// Elements to search
int target1 = 50; // Element present in the array
int target2 = 35; // Element not in the array
if (iterative_result1 != -1) {
printf("%d found at index %d (Iterative)\n", target1, iterative_result1);
} else {
printf("%d not found in the array (Iterative)\n", target1);
}
if (iterative_result2 != -1) {
printf("%d found at index %d (Iterative)\n", target2, iterative_result2);
} else {
printf("%d not found in the array (Iterative)\n", target2);
}
if (recursive_result1 != -1) {
printf("%d found at index %d (Recursive)\n", target1, recursive_result1);
} else {
printf("%d not found in the array (Recursive)\n", target1);
}
if (recursive_result2 != -1) {
printf("%d found at index %d (Recursive)\n", target2, recursive_result2);
} else {
printf("%d not found in the array (Recursive)\n", target2);
}
return 0;
}
/*
Binary Search Key Characteristics:
1. PREREQUISITES:
- Array MUST be sorted in ascending order
- Elements must be comparable and have a natural ordering
2. Time Complexity:
- Best Case: O(1) - when middle element is the target
- Worst Case: O(log n) - when target is at the beginning/end or not present
- Average Case: O(log n)
3. Space Complexity:
- Iterative Version: O(1) - uses constant extra space
- Recursive Version: O(log n) - due to recursive call stack
4. Advantages:
- Extremely efficient for large sorted arrays
- Dramatically reduces search space in each iteration
- Much faster than linear search for large datasets
5. Disadvantages:
- Requires sorted array (preprocessing cost)
- Not suitable for unsorted arrays
- Less efficient for small arrays due to overhead
- More complex implementation compared to linear search
Comparison Notes:
- Linear Search: O(n) time complexity
- Binary Search: O(log n) time complexity
- Binary search becomes significantly more efficient as array size increases
*/