Modified binary search algorithm
More...
#include <stdio.h>
#include <stdlib.h>
|
int | binarySearch (const int **mat, int i, int j_low, int j_high, int x) |
| This function does Binary search for x in i -th row from j_low to j_high . More...
|
|
void | modifiedBinarySearch (const int **mat, int n, int m, int x) |
| Function to perform binary search on the mid values of row to get the desired pair of rows where the element can be found. More...
|
|
int | main () |
| Main function.
|
|
◆ binarySearch()
int binarySearch |
( |
const int ** |
mat, |
|
|
int |
i, |
|
|
int |
j_low, |
|
|
int |
j_high, |
|
|
int |
x |
|
) |
| |
This function does Binary search for x
in i
-th row from j_low
to j_high
.
- Parameters
-
mat | 2D matrix to search within |
i | row to search in |
j_low | start column index |
j_high | end column index |
x | value to search for |
- Returns
- column where
x
was found
-
-1 if value not found
20 while (j_low <= j_high)
22 int j_mid = (j_low + j_high) / 2;
25 if (mat[i][j_mid] == x)
27 printf(
"Found at (%d,%d)\n", i, j_mid);
30 else if (mat[i][j_mid] > x)
37 printf(
"element not found\n");
◆ modifiedBinarySearch()
void modifiedBinarySearch |
( |
const int ** |
mat, |
|
|
int |
n, |
|
|
int |
m, |
|
|
int |
x |
|
) |
| |
Function to perform binary search on the mid values of row to get the desired pair of rows where the element can be found.
- Parameters
-
[in] | mat | matrix to search for the value in |
| n | number of rows in the matrix |
| m | number of columns in the matrix |
| x | value to search for |
58 int i_low = 0, i_high = n - 1, j_mid = m / 2;
59 while ((i_low + 1) < i_high)
61 int i_mid = (i_low + i_high) / 2;
63 if (mat[i_mid][j_mid] == x)
65 printf(
"Found at (%d,%d)\n", i_mid, j_mid);
68 else if (mat[i_mid][j_mid] > x)
74 if (mat[i_low][j_mid] == x)
75 printf(
"Found at (%d,%d)\n", i_low, j_mid);
76 else if (mat[i_low + 1][j_mid] == x)
77 printf(
"Found at (%d,%d)\n", i_low + 1, j_mid);
80 else if (x <= mat[i_low][j_mid - 1])
84 else if (x >= mat[i_low][j_mid + 1] && x <= mat[i_low][m - 1])
88 else if (x <= mat[i_low + 1][j_mid - 1])