美文网首页
敲代码的第。。。天,一道很简单的面试题

敲代码的第。。。天,一道很简单的面试题

作者: Aa土豆 | 来源:发表于2019-06-28 22:21 被阅读0次

今天碰到一个非常非常简单的面试题,但是我还是在规定的时间没有写出来,借此纪念一下。

/*

面试题:

给定一个有序的数组,如果往该数组中存储一个元素,并保证这个数组还是有序的,那么这个元素存储的角标如何获取

*/

class ArrayDemo

{

public static void main(String[] args)

{

int[] arr = {2,5,7,12,15,17,19,30,39,48,89,90};

int index = halfSearch(arr,1);

System.out.println(index);

}

public static int halfSearch(int[] arr,int key)

{

  int max,min,mid;

  max = arr.length - 1;

  min = 0;

  while(min <= max)

  {

  mid = (max + min) / 2;

if(key > arr[mid])

min = mid + 1;

else if(key < arr[mid])

max = mid - 1;

else

return mid;

  }

return min;

}

}

相关文章

网友评论

      本文标题:敲代码的第。。。天,一道很简单的面试题

      本文链接:https://www.haomeiwen.com/subject/cgyycctx.html