fork download
  1. #include <stdio.h>
  2.  
  3. #define M 7
  4. #define N 7
  5.  
  6. int binarySearch(double row[], int size, double target) {
  7. int left = 0, right = size - 1;
  8. while (left <= right) {
  9. int mid = left + (right - left) / 2;
  10. if (row[mid] == target) {
  11. return mid;
  12. } else if (row[mid] < target) {
  13. right = mid - 1;
  14. } else {
  15. left = mid + 1;
  16. }
  17. }
  18. return -1;
  19. }
  20.  
  21. int main() {
  22. double matrix[M][N];
  23. double X;
  24.  
  25. printf("Enter the elements of the matrix (%d x %d), sorted in non-increasing order (row by row):\n", M, N);
  26. for (int i = 0; i < M * N; i++) {
  27. scanf("%lf", &matrix[i / N][i % N]);
  28. }
  29.  
  30. printf("Enter the number X to search for: ");
  31. scanf("%lf", &X);
  32.  
  33. printf("\nInput matrix:\n");
  34. for (int i = 0; i < M; i++) {
  35. for (int j = 0; j < N; j++) {
  36. printf("%6.2lf ", matrix[i][j]);
  37. }
  38. printf("\n");
  39. }
  40.  
  41. for (int i = 0; i < M; i++) {
  42. int index = binarySearch(matrix[i], N, X);
  43. if (index != -1) {
  44. printf("Number %.2lf found in row %d at position %d.\n", X, i, index);
  45. } else {
  46. printf("Number %.2lf not found in row %d.\n", X, i);
  47. }
  48. }
  49.  
  50. return 0;
  51. }
  52.  
Success #stdin #stdout 0s 5272KB
stdin
Standard input is empty
stdout
Enter the elements of the matrix (7 x 7), sorted in non-increasing order (row by row):
Enter the number X to search for: 
Input matrix:
  0.00   0.00   0.00   0.00   0.00   0.00   0.00 
  0.00   0.00   0.00   0.00   0.00   0.00   0.00 
  0.00   0.00   0.00   0.00   0.00   0.00   0.00 
  0.00   0.00   0.00   0.00   0.00   0.00   0.00 
  0.00   0.00   0.00   0.00   0.00   0.00   0.00 
  0.00   0.00   0.00   0.00   0.00   0.00   0.00 
  0.00   0.00   0.00   0.00   0.00   0.00   0.00 
Number 0.00 not found in row 0.
Number 0.00 not found in row 1.
Number 0.00 not found in row 2.
Number 0.00 not found in row 3.
Number 0.00 not found in row 4.
Number 0.00 not found in row 5.
Number 0.00 not found in row 6.