0

I want to know the exact time complexity of my algorithm in this method. I think it is nlogn as it uses arrays.sort;

public static int largestElement(int[] num) throws NullPointerException // O(1)
    {
    int a=num.length; // O(1)
    Arrays.sort(num); // O(1)? yes

    if(num.length<1) // O(1)
    return (Integer) null;
    else
    return num[a-1]; // O(1)
    }
OmG
  • 18,337
  • 10
  • 57
  • 90
Internet
  • 17
  • 1
  • 5
  • _Arrays.sort(num); // O(1)?_ yes - no it is `n*log(n)` – jmj Nov 06 '13 at 01:09
  • Sorting an array will not result to an O(1) complexity: http://stackoverflow.com/questions/753237/what-sort-does-java-collections-sortnodes-use http://en.wikipedia.org/wiki/Sorting_algorithm – Nick Louloudakis Nov 06 '13 at 01:10

3 Answers3

2

You seem to grossly contradict yourself in your post. You are correct in that the method is O(nlogn), but the following is incorrect:

Arrays.sort(num); // O(1)? yes

If you were right, the method would be O(1)! After all, a bunch of O(1) processes in sequence is still O(1). In reality, Arrays.sort() is O(nlogn), which determines the overall complexity of your method.

Finding the largest element in an array or collection can always be O(n), though, since we can simply iterate through each element and keep track of the maximum.

arshajii
  • 127,459
  • 24
  • 238
  • 287
1

Indeed, it is O(nlogn). Arrays.sort() uses merge sort. Using this method may not be the best way to find a max though. You can just loop through your array, comparing the elements instead.

damat-perdigannat
  • 5,780
  • 1
  • 17
  • 33
1

"You are only as fast as your slowest runner" --Fact

So the significant run time operations here are your sorting and your stepping through the array. Since Arrays.sort(num) is a method which most efficiently sorts your arrays, we can guarantee that this will be O(nlg(n)) (where lg(n) is log base 2 of n). This is the case because O notation denotes the worst case runtime. Furthermore, the stepping of the array takes O(n).

So, we have O(nlgn) + O(n) + O(1) + ...

Which really reduces to O(2nlg(n)). But co-efficient are negligible in asymptotic notation. So your runtime approaches O(nlg(n)) as stated above.

bneigher
  • 818
  • 4
  • 13
  • 24