glockm15
glockm15

Reputation: 245

Using Arrays library to merge sort an int array

I want to use the function

public static void sort(Object[] a)

To sort an int array but I am not sure how to do it so that I know definitely sure that it is using the merge sort and not any other sort.

Here is the Java documentation: https://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html

And below is what I think would be a correct implementation of the function in order to use the merge sort.

 public static void main(String[] args) {
     int arr[] = { 3, 2, 4, 1, 99, 30, 5, 3 };
     Arrays.sort(arr);
 }

Would this be correct? And further I wanted to specify an index from where to start sorting etc with

sort(Object[] a, int fromIndex, int toIndex)

How would I make sure to write up the code so that it used the merge sort and not quick sort.

Upvotes: 1

Views: 3194

Answers (3)

YK S
YK S

Reputation: 3440

There is a legacy Merge Sort implementation in Arrays utility class encapsulated inside LegacyMergeSort class.

As mentioned by-default Arrays.sort will not use it. So you need to instruct the jvm to use it. This is as per the Java docs:

  Old merge sort implementation can be selected (for
  compatibility with broken comparators) using a system property.

The system property is java.util.Arrays.useLegacyMergeSort=true and you can set it either using java -Djava.util.Arrays.useLegacyMergeSort=true jar or using System.setProperty("java.util.Arrays.useLegacyMergeSort",true);

Upvotes: 0

dZ.
dZ.

Reputation: 404

Arrays.sort method normally uses Quick Sort for arrays of primitives and Merge Sort for arrays of objects.

Therefore, in order to use Merge Sort, I guess you have to declare your array as an Integer object array, e.g.

// Unsorted array
Integer[] a = { 2, 6, 3, 5, 1 };

Upvotes: 1

karlPet
karlPet

Reputation: 44

Unfortunately, Arrays.sort uses both! It seems like, for your integer implementation it uses quicksort.

https://cafe.elharo.com/programming/java-programming/why-java-util-arrays-uses-two-sorting-algorithms/

Upvotes: 0

Related Questions