简体   繁体   中英

How efficient is Arrays.sort(…) for a 2 Million elements arrays that is already sorted

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.

For primitives arrays

Best case performance   O(n log n)

Worst case performance  O(n2) 

For more detailed information read : http://en.wikipedia.org/wiki/Quicksort

For Object[] array

Worst case performance  O(n log n)
Best case performance   O(n)

For more detailed information read : http://en.wikipedia.org/wiki/Timsort

对于每个线程 ,由于Arrays.sort()使用Quicksort的修改版本,因此无论数组是否已排序,排序运行时均为O(n*log n)

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM