【发布时间】:2017-08-03 12:41:02
【问题描述】:
所以我对算法很陌生,并且从未使用递归编程,所以如果我错过了一些愚蠢的东西,我提前道歉。
我正在尝试制作一种搜索算法,我相信它的工作方式类似于二进制搜索。
让我们调用搜索 x 的元素(就像 x 标记该点)
So I search a random index in a sorted array
If element < x
lowerbound = index + 1 //to create a sub array
If element > x
upperbound = index - 1 //to create a sub array
Repeat process until find x in array.
我遇到的问题是我的随机数只能在范围内搜索。如果我像在我的代码中那样去rand.nextInt(upperbound),它只会继续向左搜索。我需要能够向左或向右搜索它。有没有更好的随机数方法呢?有谁知道我怎么可能实现这个算法?下面的代码是一天半的工作,老实说,我现在对自己很失望。
另外我知道如果我的数组根本不包含 x 但我想首先对基本搜索机制进行排序,我还需要考虑这种情况。
任何帮助将不胜感激。
private static int counter = 0;
public static int searchRan(int Array[], int x, int low, int up)
{
counter++;
Random rand = new Random();
int select = rand.nextInt(up);
System.out.println(select);
if(Array[select] == x)
{
System.out.printf("Found %d after %d recursion", x, counter);
return select;
}
else if(Array[select] < x)
{
return searchRan(Array, x, select + 1, up);
}
else if(Array[select] > x)
{
return searchRan(Array, x, low, select - 1);
}
else
{
return 666;
}
}
public static void main(String[] args){
int sortedArray[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
int lowerbound = 0;
int upperbound = sortedArray.length - 1;
int target = 0;
System.out.println(searchRan(sortedArray, 0, lowerbound, upperbound));
}
【问题讨论】:
-
是否可以让递归参数的数组更小以达到预期的效果? return searchRan(Array, x, select + 1, up);