0

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.
5
  • Do your numbers always increment by a fixed amount (5 in the given example)? Commented Apr 17, 2012 at 15:45
  • Use for (int i=0, ...) in your for loops, otherwise be aware your i variable can be changed somewhere else in your method. Commented Apr 17, 2012 at 15:47
  • @Ozzy, no I do that. My codes o/P is correct. No issue with that. I want faster one. Commented Apr 17, 2012 at 15:48
  • 1
    You could try putting the values of array2, array3, etc into HashSet<Integer>, and then simply call set2.contains(element); Commented Apr 17, 2012 at 16:00
  • @GregCase, that is now I am thinking. Cool way. Commented Apr 17, 2012 at 16:03

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

2 Comments

your answer is correct. But, I forgot to mention something. I modified my question.
If the array size is always very small, then the linear search you're already doing is the best way to do it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.