简体   繁体   中英

Should I use java collection sort() or implement my own?

I have an array that I need to sort the values in increasing order. The possible value inside the array are is between 1-9, there will be a lot of repeating value. (fyi: I'm working on a sudoku solver and trying to solve the puzzle starting with the box with least possibilities using backtracking)

The first idea that comes to my mine is to use Shell Sort.

I did some look up and I found out that the java collection uses "modified mergesort"(in which the merge is omitted if the highest element in the low sublist is less than the lowest element in the high sublist).

So I wish to know if the differences in performance will be noticeable if I implement my own sorting algorithm.

If you only have 9 possible values, you probably want counting sort - the basic idea is:

  • Create an array of counts of size 9.

  • Iterate through the array and increment the corresponding index in the count array for each element.

  • Go through the count array and recreate the original array.

The running time of this would be O(n + 9) = O(n) , where-as the running time of the standard API sort will be O(n log n) .

So yes, this will most likely be faster than the standard comparison-based sort that the Java API uses, but only a benchmark will tell you for sure (and it could depend on the size of your data).


In general, I'd suggest that you first try using the standard API sort , and see if it's fast enough - it's literally just 1 line of code (except if you have to define a comparison function), compared to quite a few more for creating your own sorting function, and quite a bit of effort has gone into making sure it's as fast as possible, while keeping it generic.

If that's not fast enough, try to find and implement a sort that works well with your data. For example:

  • Insertion sort works well on data that's already almost sorted (although the running time is pretty terrible if the data is far from sorted).

  • Distribution sorts are worth considering if you have numeric data.


As noted in the comment, Arrays.parallelSort (from Java 8) is also an option worth considering, since it multi-threads the work (which sort doesn't do, and is certainly quite a bit of effort to do yourself ... efficiently).

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