-4

I have noticed odd behavior when using Java Arrays.sort() on sub-arrays. Here is a demo program. Is this a bug in Java?

package sorted_subsegments;

import java.util.Arrays;

public class sortTest {
    public static void main(String[] args) {
        int A[] = {3, 2, 1};
        System.out.format("A: %s\n", Arrays.toString(A));
        Arrays.sort(A, 0, 1);
        System.out.format(" after sub array sort on A: %s\n", Arrays.toString(A));
        System.out.println("Should be A: [2, 3, 1]");
        Arrays.sort(A);
        System.out.format(" whole array sort on A: %s\n", Arrays.toString(A));
    }
}
SaSConsul
  • 298
  • 2
  • 9
  • And the result is? – VLEFF Jun 24 '16 at 08:20
  • 1
    What is your problem? – Blank Jun 24 '16 at 08:20
  • 1
    Have you read [the javadoc](https://docs.oracle.com/javase/8/docs/api/java/util/Arrays.html#sort-int:A-int-int-)? "toIndex - the index of the last element, ***exclusive***, to be sorted" – assylias Jun 24 '16 at 08:21
  • 4
    Java is already more than 20 years old, and this method has existed since the beginning - you can be quite sure that it does not contain a bug that would be so obvious. – Jesper Jun 24 '16 at 08:31
  • @assylias thank-you. I have been too much late night programming to read the doc correctly. – SaSConsul Jun 24 '16 at 08:37

1 Answers1

6

From the Javadoc

fromIndex - the index of the first element, inclusive, to be sorted

toIndex - the index of the last element, exclusive, to be sorted

The second index (toIndex) is NOT included in the range to be sorted.

So, in your example

Arrays.sort(A, 0, 1);

you are sorting only element [0] of the array, which does nothing.

Community
  • 1
  • 1
Jim Garrison
  • 85,615
  • 20
  • 155
  • 190