1

this (obvious) code i've writen works well, but for testing purposes, i should make it work for a "one million" sized array in a reasonable time by saving CPU Cycles and saving as much memory as i can.
any suggestions please?
!!! the array is arranged in ascending order !!!

import java.util.Arrays;

class A {
static boolean exists(int[] ints, int k) {
    for(int integer : ints){
        if(integer == k){
            return true; 
        }
    }
    return false;
}

2 Answers2

2

Since your array is in ascending order, one thing you could do (i think) is to make a binary search instead of a linear search.

George Z.
  • 6,643
  • 4
  • 27
  • 47
1

You could use a Set<Integer> that relies on hashing rather than an array where you iterate sequentially.

static boolean exists(Set<Integer> ints, int k) {
     return ints.contains(k);
}

You could convert the array to a Set and pass it to the method as many times as required :

Set<Integer> set = Arrays.stream(ints).boxed().collect(Collectors.toSet());
boolean isExist = exists(set, 15);
 ...
isExist = exists(set, 5005);
 ...
isExist = exists(set, 355);
davidxxx
  • 125,838
  • 23
  • 214
  • 215