0
基本上,为了修改目的,试图在处理中编码二进制搜索算法。决定使用Processing以方便使用。任何人都可以发现错误,因为它让我困惑。谢谢:)处理中的二进制搜索,ArrayIndexOutOfBounds
//Set size and font information.
size(400, 200);
background(0,0,0);
PFont font;
font = loadFont("Arial-Black-14.vlw");
textFont(font);
//Initialise the variables.
int[] intArray = new int[10];
int lower = 1;
int upper = 10;
int flag = 0;
int criteria = 10;
int element = 0;
//Populate the Array.
for(int i=0; i<10; i++)
{
intArray[i] = i;
}
//Tell the user Array is filled.
text("Array Filled", 15, 20);
// Main loop.
while(flag == 0)
{
//Sets the element to search by finding mid point.
element = ((lower+upper)/2);
//Checks if the mid point is equal to search criteria.
if(intArray[element] == criteria)
{
flag = 1;
}
//Checks if the criteria is grater than the currently searched element.
else if(criteria > intArray[element])
{
lower = (element+1);
}
else
{
upper = (element-1);
}
//Checks if the lower value is higher than the upper value.
if(lower > upper)
{
flag = 2;
}
}
//If no match is found.
if(flag == 2)
{
text("Did not find criteria "+criteria, 15, 40);
}
//If a match is found.
else
{
text("Found "+criteria+" at index "+element+"", 15, 60);
}
此外,您正在搜索10,但十个不在数组中,0到9是。代码应该仍然有效,它只会返回它没有找到元素。 – Oskar 2011-04-27 20:26:27
棒极了,欢呼的队友。不知道我是如何错过的。 – 2011-04-27 20:29:54
不用担心!容易犯的错误:) – Oskar 2011-04-27 20:37:55