Java查找数组中的元素

时间:2012-04-17 15:43:45

标签: java

我有五个数组,我存储传入的int数字,如:

int array1 = {1,6,..}
int array2 = {2,7,..}
.
.
int array5 = {5,10,..}

现在,我要做的是,在另一个数组中搜索下一个数字。

喜欢,

for(i = 0, i < array1.size ; i++){

int element = array1[0] ;

//here array2, array3, ..., array5 can have different size
search for array2 to find element+1
search for array3 to find element+2
.
.
search for array5 to find element+5
}

我现在正在做的是:

Run for loop for 0 to array2 size, to find element+1 (so for others)

然而,它很慢。任何人都可以给我一些想法,如何让它更快(我可以将数组更改为任何其他数据结构)。

对不起,我在提问时犯了两个错误,我应该提到:

1) Arrays are sorted (incremental elements always).
2) Array elements are very few (2-3) so Binary Search will be expensive.
3) I have to perform the search for thousand times means when channel input pause, I have to perform search, then again channel start and I have to perform search ... so on.

1 个答案:

答案 0 :(得分:4)

如果数组已排序,请使用二进制搜索来查找元素,而不是为每个元素循环。