D
D
Dmitriy2019-12-15 16:35:03
C++ / C#
Dmitriy, 2019-12-15 16:35:03

How to use binary search to find the very first element of a matrix from a range?

This code for finding a specific element, not a range in a one-dimensional array - WORKS!

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>


int main() {
  int arr2[7] = { -2, -1, 0, 1, 2, 3, 4 };
  printf("This is arr2!\n=============\n");
  for (int i = 0; i < 7; i++) {
    printf(" %i |", arr2[i]);	
  }
  printf("\n=============\n");

  int left = 0;
  int right = 6;
  while (left <= right) {
    int mid = (left + right) / 2;
    if (arr2[mid] < 3) {
      left = mid + 1;
    }
    else if (arr2[mid] > 3) {
      right = mid - 1;
    }
    else {
      printf("Needed value is with index = %i!", mid);
      return 0;
    }
  }
  return 0;
}

Below code for binary search in a matrix - only works for a specific, single number, not a range!
But it does not check for duplicate elements.
If string = [-5, -2, -1, -1, 6, 7, 9]. We are looking for -1 , then the search will select -1 with index 3, not 2.
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

int main() {
  int arr[7][7] = { {-5, -2, -1, 1, 6, 7, 8},
          {-91, 6, 6, 7, 7, 8, 9},
          {-10, -1, 6, 7, 8, 9, 10},
          {-1, -1, 7, 8, 8, 8, 9},
          {-10, -8, -5, -1, -1, 7, 8},
          {-3, -2, -1, -1, 6, 7, 8},
          {1, 4, 13, 22, 31, 40, 52},
          };

  for (int i = 0; i < 7; i++) {
    for (int j = 0; j < 7;j++) {
      printf("%d", arr[i][j]);
      printf(" ");
    }
    printf("\n");
  }
 for (int k = 0; k < 7; k++) {
    int mid = 0;
    int left = 0;
    int right = 6;
    while (left <= right) {
      mid = (right + left) / 2;
      if (arr[k][mid] < 1) {
        left = mid + 1;
      }
      else if (arr[k][mid] > 1) {
        right = mid - 1;
      }
      else {
        printf("Needed value [%i] is with index = [%i]:[%i]!", arr[k][mid], k, mid);
        
        return 0;
      }
    }
  }
  return 0;
}

What's wrong, tell me please!

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question