I need to execute another sorting for an array of 2 Million elements using Arrays.sort(..) method. In order not to keep another dirty flag like, I was wondering how costly is this method call for an already sorted array.
Any thoughts?
I need to execute another sorting for an array of 2 Million elements using Arrays.sort(..) method. In order not to keep another dirty flag like, I was wondering how costly is this method call for an already sorted array.
Any thoughts?
It depends on the content of your array. Sorting primitives uses a dual-pivot Quick Sort, as per the docs. This has an amortized complexity of O(n logn)
, though worst case is O(n^2)
Sorting Objects uses TimSort (docs), a modified Merge Sort. According to the docs, TimSort for a nearly-sorted (or, presumably, sorted) array takes approximately n
comparisons.
It would be far cheaper still for you to keep a dirty flag rather than suffer the O(n)
compares.
Best case performance O(n log n)
Worst case performance O(n2)
For more detailed information read : http://en.wikipedia.org/wiki/Quicksort
Worst case performance O(n log n)
Best case performance O(n)
For more detailed information read : http://en.wikipedia.org/wiki/Timsort
Per this thread, the sorting runtime will be O(n*log n)
since Arrays.sort()
uses a modified version of quicksort, whether the array is already sorted or not.
Array.sort() uses the best case complexity scenario of O(n log n) to sort an array by using Merge Sort which in turn uses divide and conquer approach. In the best case where you already have a sorted array the Best Possible Case could be O(n).