int data[] = new int [] {1,2,3,4,5,6,7,8};
int search = 7;
public static int index(int arr[],int key)
{
for(int x = 0 ;x<arr.length;x++)
{
if(arr[x] == key)
{
return x;
}
}
return -1;
}
时间复杂度为n,更快速的查找操作,二分查找 前提:数组排序(有序数组)
二分关键值在于中间 实现二分查找,方法递归完成
public static int binarySearch(int arr[],int from ,int to ,int key)
{
if(from< to)
{
int mid = (from/2) + (to/2)
if(arr[mid]==key)
return mid;
else if(key<arr[mid])
{
return binarySearch(arr,from,mid-1,key)
}
else if(key>arr[mid])
{
return binarySearch(arr,mid+1,to,key)
}
}
return -1;
}
数据结构的训练