From ccd3f6660870626e2b9d1c679e609e924753306b Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Wed, 1 Jul 2020 21:27:12 -0400 Subject: [PATCH] fix code - major errors + add docs --- searching/modified_binary_search.c | 45 ++++++++++++++++++++++-------- 1 file changed, 34 insertions(+), 11 deletions(-) diff --git a/searching/modified_binary_search.c b/searching/modified_binary_search.c index 7a4d0039..c376a90b 100644 --- a/searching/modified_binary_search.c +++ b/searching/modified_binary_search.c @@ -1,10 +1,21 @@ +/** + * @file + * @brief [Modified binary search algorithm](https://arxiv.org/abs/1406.1677) + */ #include #include -int n, m; // size of the matrix - -// This function does Binary search for x in i-th row from j_low to j_high. -void binarySearch(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`. + * @param mat 2D matrix to search within + * @param i row to search in + * @param j_low start column index + * @param j_high end column index + * @param x value to search for + * @return column where `x` was found + * @return -1 if value not found + */ +int binarySearch(const int **mat, int i, int j_low, int j_high, int x) { while (j_low <= j_high) { @@ -14,20 +25,27 @@ void binarySearch(int **mat, int i, int j_low, int j_high, int x) if (mat[i][j_mid] == x) { printf("Found at (%d,%d)\n", i, j_mid); - return; + return j_mid; } else if (mat[i][j_mid] > x) j_high = j_mid - 1; else j_low = j_mid + 1; } + // element not found printf("element not found\n"); + return -1; } -// Function to perform binary search on the mid values of row to get the desired -// pair of rows where the element can be found -void modifiedBinarySearch(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 + * @param [in] mat matrix to search for the value in + * @param n number of rows in the matrix + * @param m number of columns in the matrix + * @param x value to search for + */ +void modifiedBinarySearch(const int **mat, int n, int m, int x) { // If Single row matrix if (n == 1) { @@ -75,12 +93,16 @@ void modifiedBinarySearch(int **mat, int n, int m, int x) binarySearch(mat, i_low + 1, j_mid + 1, m - 1, x); } +/** Main function */ int main() { - int x; // element to be searched + int x; // element to be searched + int m, n; // m = columns, n = rows + scanf("%d %d %d\n", &n, &m, &x); + int **mat = (int **)malloc(n * sizeof(int *)); - for (x = 0; x < n; x++) mat[x] = (int *)malloc(m * sizeof(int)); + for (int i = 0; i < m; i++) mat[i] = (int *)malloc(m * sizeof(int)); for (int i = 0; i < n; i++) { @@ -89,9 +111,10 @@ int main() scanf("%d", &mat[i][j]); } } + modifiedBinarySearch(mat, n, m, x); - for (x = 0; x < n; x++) free(mat[x]); + for (int i = 0; i < n; i++) free(mat[i]); free(mat); return 0; }