Tuesday, 19 August 2014

4 Examples to Sort Array in Java


 http://www.quontrasolutions.com/blog/wp-content/uploads/2014/07/111.png

You can use Arrays.sort() method to sort both primitive and object array in Java. This method sorts given array into ascending order, which is numeric order for primitives and defined by compareTo() or compare() method for objects. For primitive arrays e.g. int,  short, character, float, double or long this method uses  dual-pivot Quicksort sorting algorithm implemented by Vladimir Yaroslavskiy, Jon Bentley, and Joshua Bloach (author of Effective Java) .

This algorithm offers O(n log(n)) performance on many data sets that cause other quicksort algorithms to degrade into their worst quadratic performance e.g. O(n^2), and is typically faster than traditional (one-pivot) Quicksort implementations. That’s why I always said that prefer library method your own, you can get it right but amount of exposure library method gets, you will never get for your implementations. On the other hand object array is sorted using stable MergeSort algorithm, which ensures that equal elements keep their original position in sorted array. Implementation of mergesort used in sort(Object[]) is stable, adaptive, and iterative that requires much lesser than O(n log(n)) comparisons when the input array is partially sorted, while offering the performance of a traditional mergesort when the input array is randomly ordered. In best case, when input array is almost sorted, this implementation requires approximately O(n) comparisons.

By the way temporary storage requirements vary from a small constant for nearly sorted input arrays to n/2 object references for randomly ordered input arrays. In order to sort different types of array in Java, you can use any of the overloaded version of sort() method from Arrays class. It also has two special method for sorting object array, one sorts the array in natural order, while other sort them in custom order of provided comparator. Since two dimensional array is also array of array in Java, you can use any this method to sort multi dimensional array in Java also. We will see step by step examples of sorting all kinds of array in Java in subsequent section.

For more Visit: http://www.quontrasolutions.com/blog/category/java

No comments:

Post a Comment