I need to know the time complexity of the sortedArrayUsingComparator function of the NSArray class. A source would be great since I'm likely to mention it in my bachelor's thesis. I'm sorting an array of locations by distance to the current location.
The only answer I could find was someone saying it was at least T(n)=O(n) but likely T(n)=O(n log n)
How would I know for sure?
In Big O, there are six major types of complexities (time and space): Constant: O(1) Linear time: O(n) Logarithmic time: O(n log n)
Glossary. Quasilinear Time - O(n log n): Given a data set of size n , the algorithm executes an n number of operations where each operation runs in log n (logarithmic) time.
O(nlogn) is known as loglinear complexity. O(nlogn) implies that logn operations will occur n times. O(nlogn) time is common in recursive sorting algorithms, sorting algorithms using a binary tree sort and most other types of sorts.
By actual trial of NSArray sorting the times are in line with O(n*log(n))
.
See blog post
Note that in a comment there is a sort method (PS9110) which is O(n) but is proprietary and patented. The method is quite interesting.
Well to sort an array you have to at least look at every element which is for sure O(n)
. There are several mathematical papers which show you that there can't be a better sorting algorithm then O(n*log(n))
like Mergesort
for example. Since the comparator implements a Mergesort
I think the complexity should be O(n*log(n))
for best,average and worst case.
You can find some information about Mergesort
here:
Mergesort
And some article concerning the best sorting algorithm time complexity: Sorting algorithms
I couldn't find the exact implementation of the given method but here is a great article how you can dig deeper in the implementation of Arrays in Objective-C and to have a look at the methods implementation: Exposing NSMutableArray
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With