Sorting in Java

 Java provides two in-built methods for sorting - Arrays.sort() and Collections.sort(). The former is used for arrays of primitive types such as int, char, etc., and arrays of object types such as String, Integer, Student (a user-defined class), etc. On the other hand, the latter is used to sort elements in a collection, such as ArrayList and LinkedList.

It's worth noting that collections are only available for non-primitive types. Therefore, ArrayList and LinkedList cannot be made of primitive types like int or char, but only for non-primitive types like String or Integer. When sorting an array of non-primitives, it's preferred to use a stable sorting algorithm that maintains the existing order. For instance, suppose we have an array of Student objects that contain branch and rollNo information. In that case, the array should be sorted by branch, and the result should maintain the existing order of students within each branch.

Consider the following example of an array in sorted order:

{CS, 101}, {ECE, 102}, {CS, 104}, {CS, 105}, {ECE, 107}

If we need to segregate the students by their branches, two cases might arise: unstable sorting and stable sorting.

Unstable sorting according to branch would mean that the existing order is not maintained. For instance, {CS, 104} might come before {CS, 101}. However, stable sorting ensures that the existing order is maintained, resulting in the following sorted array:

{CS, 101}, {CS, 104}, {CS, 105}, {ECE, 102}, {ECE, 107}

When dealing with primitive types, the ordering does not matter, and an unstable sorting algorithm might be faster. Therefore, the dual pivot quicksort algorithm is used for primitive types. On the other hand, sorting non-primitives is based on the merge-sort algorithm, which is an adaptation of the timsort algorithm, ensuring stability in the sorting process.

In conclusion, understanding the differences between sorting algorithms for primitive and non-primitive types can help you choose the appropriate sorting method in your code.

Previous Post Next Post