黑马程序员技术交流社区
标题:
从一个排列好的数中查找索引!
[打印本页]
作者:
冯超
时间:
2013-5-4 13:00
标题:
从一个排列好的数中查找索引!
有一个已经排好序的数组,现在输入一个数
问,现在要你编写一个函数,去得到这个数的索引
:
package interview;
public class test1 {
/**
* @param args
* 有一个已经排好序的数组,现在输入一个数
* * 问,现在要你编写一个函数,去得到这个数的索引
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int arr[] = new int[] {1,2,3,4,5,6,7,8,20};
int index = getIndex(0, arr, 5, 2);
System.out.println(index);
}
public static int getIndex(int startIndex, int a[], int lastIndex, int data) {
int index = -1;
//判断输入的数字是否合法
if(startIndex - lastIndex >= 0)
return -1;
if(data < a[startIndex] || data > a[lastIndex])
return -1;
//以下是查找索引的方法
int fist = startIndex;
int last = lastIndex;
int mid = (fist + last) / 2;
while(fist <= last) {
if(data == a[mid])
return mid;
if(data > a[mid])
fist = mid + 1;
if(data < a[mid])
last = mid - 1;
mid = (fist + last) / 2;
}
return index;
}
}
复制代码
作者:
冯超
时间:
2013-5-4 13:01
··不知道还有没有什么更好的方法!
作者:
乘鱼飞
时间:
2013-5-4 13:17
public class Test {
public static void main(String[] args) {
int arr[] = new int[] {1,2,3,4,5,6,7,8,20};
Scanner sc=new Scanner(System.in); //键盘录入
int n=sc.nextInt();
int index= searchBotey(arr,n);//自定searchBotey()方法求索引
System.out.println(n+" 的索引位置是: "+index);
}
public static int searchBotey(int[] arr,int index)
{
int num=-1;
for(int i=0;i<arr.length;i++)
{
if(index==arr[i])
num=i;
}
return num;
}
}
复制代码
输出结果:
2
2 的索引位置是: 1
作者:
冯超
时间:
2013-5-4 14:28
乘鱼飞 发表于 2013-5-4 13:17
输出结果:
2
2 的索引位置是: 1
只想说 效率太慢了
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2