#include #include #include int binary_search(float s_key, int r, int c, float matrix[r][c]) { short int mid, found; float value; found = 0; for (short int i = 0; i < r; i++) { short int start = 0; short int end = c - 1; while (start <= end) { mid = round((start + end) / 2); value = matrix[i][mid]; if (value == s_key) { printf("%.3f found at (%d, %d)\n", s_key, i+1, mid+1); found = 1; break; } else if (value < s_key) { end = mid - 1; } else { start = mid + 1; } } } if (found == 0) { printf("%.3f not found.\n", s_key); } else { return 0; } } void line_pr(short int len) { for (short int i = 0; i < len; i++) { printf("-"); } } int main () { short int rows, columns, indent, c_indent, line_len; float key, max_num; char cont; printf("Input the number of rows and columns separated with a space: "); scanf("%hd %hd", &rows, &columns); float array[rows][columns]; for (short int i = 0; i < rows; i++) { for (short int j = 0; j < columns; j++) { printf("Input a value for %hd %hd: ", i, j); scanf("%f", &array[i][j]); } } max_num = 0; for (short int i = 0; i < rows; i++) { if(array[i][0] > max_num){ max_num = array[i][0]; } } indent = floor(log10(fabs(max_num))) + 6; if (rows >= columns) { c_indent = floor(log10(rows)); } else { c_indent = floor(log10(columns)); } c_indent +=2; line_len = c_indent + indent * columns + columns * 2 + 1; printf("%*c|", c_indent, *" "); for (short int i = 1; i <= columns; i++) { printf("%*d |", indent, i); } printf("\n"); line_pr(line_len); printf("\n"); for (short int i = 0; i < rows; i++) { printf("%*d|", c_indent, i+1); for (short int j = 0; j < columns; j++) { printf("%*.3f |", indent, array[i][j]); } printf("\n"); line_pr(line_len); printf("\n"); } while(1) { printf("Input the element to search for: "); scanf("%f", &key); binary_search(key, rows, columns, array); while (1) { printf("Would you like to search again [y/n]: "); scanf(" %c", &cont); if (cont == 'y') { break; } else if (cont == 'n') { return 0; } else { printf("Improper answer, try again.\n"); } } } }