Best way to search for an element in integer array
Raj Kumar Bindal
Ranch Hand
Joined: Apr 15, 2006
Posts: 409
posted
0
I have an integer array. Elements in this array are not in any particular order. What is the best and most efficient way to find an element in this array.
If you are only going to have to do it once? Start at the beginning and go the array until you find the element, or don't find it.
If you are going to have to do it many, many times? Sort the array and use a binary search.
Raj Kumar Bindal
Ranch Hand
Joined: Apr 15, 2006
Posts: 409
posted
0
I need to search only once. But, i was just thinking if there can be any better approach than using linear search.May be if we can use some data structure to optimise the performance.
Raj Kumar Bindal wrote:I need to search only once. But, i was just thinking if there can be any better approach than using linear search.May be if we can use some data structure to optimise the performance.
Absolutely, you could use some data structure. But that wasn't what you said. You said "I have an integer array. Elements in this array are not in any particular order." It's certainly true that if you had used some other data structure -- even an integer array with the elements sorted -- you could do the search faster.
Of course it might take you longer to produce that other data structure than it would take to produce the plain old unsorted integer array. You might spend more additional time or memory or whatever you meant by "performance" than you would save in searching that other data structure.
But these are just generalities. All one can really say without any particular requirements is "It depends".
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to
run our stuff on 16 servers instead of 3.
subject: Best way to search for an element in integer array