educative.io

Will this also be an acceptable solution?

public static int search(int[] arr, int key) {
    
    if(arr == null || arr.length == 0) {
      return -1;
    }

    int left = 0;
    int right = arr.length - 1;
    int mid = right / 2;
    while(left < right) {
      if(arr[mid] < arr[mid+1]) {
        if(key < arr[mid]) {
          right = mid - 1;
        }
        else if(key > arr[mid]) {
          left = mid + 1;
        }
        else {
          return mid;
        }
      }
      else {
        if(key < arr[mid]) {
          left = mid + 1;
        }
        else if(key > arr[mid]) {
          right = mid - 1;
        }
        else {
          return mid;
        }
      }

      mid = left + (right - left) / 2;
    }

    return arr[mid] == key? mid: -1;
  }

Type your question above this line.

Course: https://www.educative.io/collection/5668639101419520/5671464854355968
Lesson: https://www.educative.io/collection/page/5668639101419520/5671464854355968/5114837707259904

Hello @Peter_Litvak ,
Yes, your code is working fine for the above problem. But it is recommended to use functions for each functionality rather than writing all code in the same function.