问题:定义一个函数,接收一个数组与一个要查找的元素,如果该元素存在数组中,那么返回该元素在数组中的索引值,如果不存在返回-1。package com.blackhorse.practise;public class Demo7 { public static void main(String[] args) { // TODO 自动生成的方法存根 int[] s = {2,4,6,5,7,9,8}; int t =getNum(s,6); System.out.println(t); } public static int getNum(int[] b,int a){ for(int i=0;i<b.length;i++){ if(a ==b[i]){ return i; }else if(a!=b[i]){ return -1; } } return 0;//程序不对,未完成 }}程序不完善,不太会写了,求大神帮助(希望高手能附上第二种写法,还能用二分查找,在此万分感谢!)
1 回答
已采纳
_潇潇暮雨
TA贡献646条经验 获得超225个赞
/**
* 查找工具类,实现简单的查找、二分查找
*/
public class FindUtil {
/**
* 构造器私有化
*/
private FindUtil() {
}
/**
* 普通查找
* @param arr数组
* @param key需要查找的关键字
* @return
*/
public static int search(int arr[], int key) {
if (arr == null || arr.length == 0) {
return -1;
}
for (int i = 0; i < arr.length; i++) {
if (key == arr[i])
return i;
}
return -1;
}
/**
* 二分查找的非递归实现 特别注意,以下算法只能针对一个升序排列的数组
*/
public static int binarySearch(int[] arr, int key) {
if (arr == null || arr.length == 0){
return -1;
}
int minIndex = 0, maxIndex = arr.length - 1, midIndex;
while (minIndex <= maxIndex) {
midIndex = (minIndex + maxIndex) >> 1; // 右移一位相当于除以2
if (key == arr[midIndex])
return midIndex;
if (key < arr[midIndex])
maxIndex = midIndex - 1;
if (key > arr[midIndex])
minIndex = midIndex + 1;
}
return -1;
}
/**
* 二分查找的递归实现---实际上是一种分治算法
*
* @param arr数组
* @param midIndex最低位置
* @param maxIndex最高位置
* @param key需要查找的值
* @return元素的位置
*/
public static int binarySearch(int[] arr, int minIndex, int maxIndex,int key) {
if (arr == null || arr.length == 0)
return -1;
if (minIndex <= maxIndex) {
int midIndex = (minIndex + maxIndex) / 2;
if (key == arr[midIndex])
return midIndex;
else if (key < arr[midIndex])
return binarySearch(arr, minIndex, midIndex - 1, key);
else
return binarySearch(arr, midIndex + 1, maxIndex, key);
} else {
return -1;
}
}
}添加回答
举报
0/150
提交
取消
