0

I have an array of 10,000 elements and i want to loop through and find a particular number say '6573'.

Example

 for(int i=0;i<=user.length;i++)
    {
        if(user[i]=="6573")
            System.out.println("Found it!!!");
    }

Could you please suggest a way to improve the performance of the code.

Thanks

Shyam
  • 6,376
  • 1
  • 24
  • 38
pal
  • 1,202
  • 6
  • 17
  • 27
  • 2
    Use a different data structure, or keep your array sorted. – Yuushi Jan 23 '14 at 05:31
  • 3
    This won't work, use `i < user.length` instead. Remember index starts at `0`! – Christian Tapia Jan 23 '14 at 05:31
  • 1
    this question belongs to [Code Review](http://codereview.stackexchange.com/) – Baby Jan 23 '14 at 05:31
  • 1
    You can never find that element with the current way. Always use `equals()` method for String value comparisons, the condition in the `for` loop must be `i < user.length`, if you want to avoid `AIOOBE` and lastly, try to use a Map if you want faster retrievals(though inserts would be time consuming). – Rahul Jan 23 '14 at 05:33

6 Answers6

2
  • Use .equals instead of == to compare strings
  • Break when a match is found
  • he end condition must be i < user.length to prevent ArrayIndexOutOfBoundsException:

--

for(int i = 0; i < user.length; i++) {
    if("6573".equals(user[i])) {
        System.out.println("Found it!!!");
        break;
    }
}

Note that I inverted the .equals() call to prevent NullPointerException if the array contains null values.

Keppil
  • 45,603
  • 8
  • 97
  • 119
2

If you need to do it once then that's about it. If you try to find several users in that list then you could use a set for O(1) search:

Set<String> set = new HashSet<>(Arrays.asList(user));
if(set.contains("6573"))
        System.out.println("Found it!!!");

And it may actually make sense to store your users directly in that set in the first place instead of using an array.

assylias
  • 321,522
  • 82
  • 660
  • 783
0

if the array elements is in order(sorted) then u can use the binary search .. it will increase the performance of your program.

Abhi Urs
  • 95
  • 3
  • 8
0

Sort the Array using sort() (efficiency O(n Log n) and use binary search (O(log n) ) .. I think this will be more efficient than your current efficency i.e, O(n).. Just giving details of @abhi's answer...

TheLostMind
  • 35,966
  • 12
  • 68
  • 104
0

try like this

int index = -1;  
boolean found = false;  
for(int i = 0; i < array.length; i++)  
{  
   if(array[i].equalsIgnoreCase(userInput))  
   {  
       index = i;
       found = true;
       break;
   }  
}
dodgy_coder
  • 12,407
  • 10
  • 54
  • 67
Shyam
  • 6,376
  • 1
  • 24
  • 38
0

you could use multi-threading and make for example 2 pointers, one travel from the start of the array and one form the end till the middle of the array.
It will use more processing but less time.

Baron Leonardo
  • 329
  • 3
  • 13