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));
}
}
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.