Arpssss
Arpssss

Reputation: 3858

Java Finding Elements in Array

I have five arrays where I store incoming int numbers like:

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

Now, what I have to do, search for next numbers in another arrays.

Like,

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
}

What I am doing right now is:

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

However, it is quite slow. Can anybody give me some idea, how to make it faster (I can change array to any-other data-structure also).

Sorry, I make two mistakes while asking, what I should mention:

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.

Upvotes: 0

Views: 165

Answers (1)

evanwong
evanwong

Reputation: 5134

If the arrays are sorted, use binary search to find the element instead of looping thru it for every single element.

Upvotes: 4

Related Questions