find smallest number in an array of n values in java code example
Example 1: find the largest and smallest number in an unsorted integer array in Java
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Number of integers to enter:");
int numberEnter = keyboard.nextInt();
int numbers[] = new int[numberEnter];
int pos = 0;
do {
System.out.printf("Please enter integer #%d/%d:%n", pos, numberEnter);
numbers[pos++] = keyboard.nextInt();
} while (pos < numberEnter && keyboard.hasNextInt());
int min = numbers[0];
int max = numbers[0];
for (pos = 1; pos < numbers.length; pos++) {
if (numbers[pos] < min) {
min = numbers[pos];
}
if (numbers[pos] > max) {
max = numbers[pos];
}
}
System.out.printf("%s Min: %d Max: %d%n", Arrays.toString(numbers),
min, max);
}
Example 2: smallest positive integer not in array java
If the expected running time should be linear, you can't use a TreeSet, which sorts the input and therefore requires O(NlogN). Therefore you should use a HashSet, which requires O(N) time to add N elements.
Besides, you don't need 4 loops. It's sufficient to add all the positive input elements to a HashSet (first loop) and then find the first positive integer not in that Set (second loop).
int N = A.length;
Set<Integer> set = new HashSet<>();
for (int a : A) {
if (a > 0) {
set.add(a);
}
}
for (int i = 1; i <= N + 1; i++) {
if (!set.contains(i)) {
return i;
}
}