#include <stdio.h>
#define M 7
#define N 7
int binarySearch( double row[ ] , int size, double target) {
int left = 0 , right = size - 1 ;
while ( left <= right) {
int mid = left + ( right - left) / 2 ;
if ( row[ mid] == target) {
return mid;
} else if ( row[ mid] < target) {
right = mid - 1 ;
} else {
left = mid + 1 ;
}
}
return - 1 ;
}
int main( ) {
double matrix[ M] [ N] ;
double X;
printf ( "Enter the elements of the matrix (%d x %d), sorted in non-increasing order (row by row):\n " , M
, N
) ; for ( int i = 0 ; i < M * N; i++ ) {
scanf ( "%lf" , & matrix
[ i
/ N
] [ i
% N
] ) ; }
printf ( "Enter the number X to search for: " ) ;
for ( int i = 0 ; i < M; i++ ) {
for ( int j = 0 ; j < N; j++ ) {
printf ( "%6.2lf " , matrix
[ i
] [ j
] ) ; }
}
for ( int i = 0 ; i < M; i++ ) {
int index = binarySearch( matrix[ i] , N, X) ;
if ( index != - 1 ) {
printf ( "Number %.2lf found in row %d at position %d.\n " , X
, i
, index
) ; } else {
printf ( "Number %.2lf not found in row %d.\n " , X
, i
) ; }
}
return 0 ;
}
I2luY2x1ZGUgPHN0ZGlvLmg+CgojZGVmaW5lIE0gNwojZGVmaW5lIE4gNwoKaW50IGJpbmFyeVNlYXJjaChkb3VibGUgcm93W10sIGludCBzaXplLCBkb3VibGUgdGFyZ2V0KSB7CiAgICBpbnQgbGVmdCA9IDAsIHJpZ2h0ID0gc2l6ZSAtIDE7CiAgICB3aGlsZSAobGVmdCA8PSByaWdodCkgewogICAgICAgIGludCBtaWQgPSBsZWZ0ICsgKHJpZ2h0IC0gbGVmdCkgLyAyOwogICAgICAgIGlmIChyb3dbbWlkXSA9PSB0YXJnZXQpIHsKICAgICAgICAgICAgcmV0dXJuIG1pZDsKICAgICAgICB9IGVsc2UgaWYgKHJvd1ttaWRdIDwgdGFyZ2V0KSB7CiAgICAgICAgICAgIHJpZ2h0ID0gbWlkIC0gMTsKICAgICAgICB9IGVsc2UgewogICAgICAgICAgICBsZWZ0ID0gbWlkICsgMTsKICAgICAgICB9CiAgICB9CiAgICByZXR1cm4gLTE7Cn0KCmludCBtYWluKCkgewogICAgZG91YmxlIG1hdHJpeFtNXVtOXTsKICAgIGRvdWJsZSBYOwoKICAgIHByaW50ZigiRW50ZXIgdGhlIGVsZW1lbnRzIG9mIHRoZSBtYXRyaXggKCVkIHggJWQpLCBzb3J0ZWQgaW4gbm9uLWluY3JlYXNpbmcgb3JkZXIgKHJvdyBieSByb3cpOlxuIiwgTSwgTik7CiAgICBmb3IgKGludCBpID0gMDsgaSA8IE0gKiBOOyBpKyspIHsKICAgICAgICBzY2FuZigiJWxmIiwgJm1hdHJpeFtpIC8gTl1baSAlIE5dKTsKICAgIH0KCiAgICBwcmludGYoIkVudGVyIHRoZSBudW1iZXIgWCB0byBzZWFyY2ggZm9yOiAiKTsKICAgIHNjYW5mKCIlbGYiLCAmWCk7CgogICAgcHJpbnRmKCJcbklucHV0IG1hdHJpeDpcbiIpOwogICAgZm9yIChpbnQgaSA9IDA7IGkgPCBNOyBpKyspIHsKICAgICAgICBmb3IgKGludCBqID0gMDsgaiA8IE47IGorKykgewogICAgICAgICAgICBwcmludGYoIiU2LjJsZiAiLCBtYXRyaXhbaV1bal0pOwogICAgICAgIH0KICAgICAgICBwcmludGYoIlxuIik7CiAgICB9CgogICAgZm9yIChpbnQgaSA9IDA7IGkgPCBNOyBpKyspIHsKICAgICAgICBpbnQgaW5kZXggPSBiaW5hcnlTZWFyY2gobWF0cml4W2ldLCBOLCBYKTsKICAgICAgICBpZiAoaW5kZXggIT0gLTEpIHsKICAgICAgICAgICAgcHJpbnRmKCJOdW1iZXIgJS4ybGYgZm91bmQgaW4gcm93ICVkIGF0IHBvc2l0aW9uICVkLlxuIiwgWCwgaSwgaW5kZXgpOwogICAgICAgIH0gZWxzZSB7CiAgICAgICAgICAgIHByaW50ZigiTnVtYmVyICUuMmxmIG5vdCBmb3VuZCBpbiByb3cgJWQuXG4iLCBYLCBpKTsKICAgICAgICB9CiAgICB9CgogICAgcmV0dXJuIDA7Cn0K