Reputation: 21
I did not figure out why the running time the Algorithm below is O(nlogn). Could anyone help me out?
public static boolean unique2(int[] data) {
int n= data.length;
int[] temp= Arrays.copyOf(data,n);
Arrays.sort(temp);
for (int j=0; j<n-1;j++)
if (temp[j]==temp[j+1])
return false;
return true;
}
Upvotes: 2
Views: 57
Reputation: 19545
This algorithm includes two main parts:
Arrays.sort
for int[]
array.Under the hood, it uses a Dual-Pivot Quicksort algorithm with average O(n log n)
time complexity.
for
loop to find any duplicate value in the sorted array with O(n)
complexity which is "absorbed" by the greater complexity of sorting.Thus, the resulting complexity is O(n log n)
.
Upvotes: 2
Reputation: 393781
Arrays.sort(temp)
takes O(nlogn)
, since that's the running time of the most efficient sorting algorithms, and the JDK implementation uses an O(nlogn)
algorithm.
The other parts of that method - Arrays.copyOf(data,n)
and the loop, take O(n)
time, since they iterate over the array one time.
Hence the overall running time is O(nlogn)
.
Upvotes: 3