C Online Compiler
Example: Optimal Matrix Search in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Optimal Matrix Search #include <stdio.h> #include <stdbool.h> // Function to search for target in matrix using optimal two-pointer approach bool searchMatrixOptimal(int matrix[5][5], int rows, int cols, int target) { // Step 1: Start from the top-right corner int row = 0; int col = cols - 1; // Step 2: Continue as long as we are within matrix bounds while (row < rows && col >= 0) { // Step 3: Compare current element with target if (matrix[row][col] == target) { return true; // Target found } else if (matrix[row][col] < target) { // Step 4: If current element is too small, move down to a larger row row++; } else { // matrix[row][col] > target // Step 5: If current element is too large, move left to a smaller column col--; } } return false; // Target not found } 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 (searchMatrixOptimal(matrix, rows, cols, target1)) { printf("Target %d found in the matrix (Optimal).\n", target1); } else { printf("Target %d not found in the matrix (Optimal).\n", target1); } // Test with target2 if (searchMatrixOptimal(matrix, rows, cols, target2)) { printf("Target %d found in the matrix (Optimal).\n", target2); } else { printf("Target %d not found in the matrix (Optimal).\n", target2); } return 0; }
Output
Clear
ADVERTISEMENTS