C Online Compiler
Example: Binary Search on Each Row in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Binary Search on Each Row #include <stdio.h> #include <stdbool.h> // Helper function for binary search on a 1D array bool binarySearch(int arr[], int size, int target) { int low = 0; int high = size - 1; while (low <= high) { int mid = low + (high - low) / 2; // Prevent overflow if (arr[mid] == target) { return true; } else if (arr[mid] < target) { low = mid + 1; } else { high = mid - 1; } } return false; } // Function to search for target in matrix using binary search on each row bool searchMatrixRowBinarySearch(int matrix[5][5], int rows, int cols, int target) { // Step 1: Iterate through each row for (int i = 0; i < rows; i++) { // Step 2: Perform binary search on the current row if (binarySearch(matrix[i], cols, target)) { return true; // Target found in this row } } return false; // Target not found in any row } int main() { int matrix[5][5] = { {1, 4, 7, 11, 15}, {2, 5, 8, 12, 19}, {3, 6, 9, 16, 22}, {10, 13, 14, 17, 24}, {18, 21, 23, 26, 30} }; int rows = 5; int cols = 5; int target1 = 5; int target2 = 20; // Test with target1 if (searchMatrixRowBinarySearch(matrix, rows, cols, target1)) { printf("Target %d found in the matrix (Binary Search per Row).\n", target1); } else { printf("Target %d not found in the matrix (Binary Search per Row).\n", target1); } // Test with target2 if (searchMatrixRowBinarySearch(matrix, rows, cols, target2)) { printf("Target %d found in the matrix (Binary Search per Row).\n", target2); } else { printf("Target %d not found in the matrix (Binary Search per Row).\n", target2); } return 0; }
Output
Clear
ADVERTISEMENTS