I am trying to design an algorithm with O(1) time complexity that returns a value from an array that isn't the smallest value. I understand that searching the array and comparing its elements to find the smallest will make the algorithm O(n), so that wouldn't work.
If I write a separate method that uses a sorting algorithm to sort the array first and then return the smallest, will this effect the time complexity of the algorithm?
Here's my code:
private static int nonSmallestElement(int[] array) {
int smallest = smallestElement(array);
int index = (int) (array.length * Math.random());
System.out.println("Index = " + index);
for (int i = index; i < array.length; i++) {
if (array[i] != smallest) {
return array[i];
}
}
return array[1];
}
private static int smallestElement(int[] array) {
Arrays.sort(array);
return array[0];
}
Here the Arrays.sort()
method is using a Dual-Pivot Quicksort algorithm, which is O(n log(n)). Does this now mean that the nonSmallestElement()
method takes on that time complexity as well, or is it O(1) because it doesn't have to handle the sort?