# Search Element in array Problem

Soumya Ranjan Mohanty
Ranch Hand
Posts: 44

i am getting Couldn't Find even if i found the element. please help me. How to omit that message for found elements.

Siddhesh Deodhar
Ranch Hand
Posts: 118
You can keep a flag whose value will change to say "true" , just before break. If value of this flag is not "true" then print "element not found"

Mohamed Sanaulla
Saloon Keeper
Posts: 3159
33
And you see- the print- "Couldn't find" executes everytime the code comes out of the loop. So as said by Siddhesh, you would have to use a flag (or even the same index- checking if its reached the end of the array) to print the message- "Couldn't Find"

Wouter Oet
Saloon Keeper
Posts: 2700
Also for searching you can use the method Arrays.binarySearch() which uses a fast searching algorithm.

Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15354
39
Also, if this is real production code (and not just an exercise) - there are more efficient ways of sorting an array than the bubble sort algorithm that you're using. There are methods for sorting arrays in class java.util.Arrays, which implement an optimized quicksort algorithm.

Campbell Ritchie
Sheriff
Posts: 49367
62
Jesper de Jong wrote:. . . There are methods for sorting arrays in class java.util.Arrays, which implement an optimized quicksort algorithm.
Only for primitives, I see from the API. For Object[] sorting, it uses a merge sort, because merge sort is "stable".

Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15354
39
Campbell Ritchie wrote:Only for primitives, I see from the API. For Object[] sorting, it uses a merge sort, because merge sort is "stable".

Aha, ok. "Stable" means that two elements that are equal will not switch order (they will be left in the original order that they were in in the array). Note that merge sort is still more efficient than bubble sort: the API docs mention that it's guaranteed O(N * log(N)) performance, whereas bubble sort has average and worst case performance of O(N^2).

Campbell Ritchie
Sheriff
Posts: 49367
62
I had always thought that sort() used merge sort throughout, but that is because I didn't read the whole of the API. That is the correct interpretation of "stable"; since primitives only have one value, there is no need for a stable sort. And bubble sort is only quicker for the very smallest arrays, otherwise it is notorious for its inefficiency.