when i run the code ,array p is not sorted. I cant figure out
why is this happening?
import java.util.Arrays;
public class Main {
public static void main (String[] args){
//creating array p
int[] p= new int[] {2,7,8,3,9,1,4,5,6,0 };
//sort p[5] to p[9]
Arrays.sort(p, 5, 9);
for(int l=0;l<p.length;l++)
{
System.out.print(p[l]);
}
}
}
output is:2783914560
You're specifically asking to sort the portion from p[5] to p[9] exclusive of the upper bound... so 4 elements, which are already in order (1, 4, 5, 6).
If you want to sort to p[9] inclusive, you should call
Arrays.sort(p, 5, 10);
From the documentation:
toIndex
- the index of the last element, exclusive, to be sorted
Of course, that still won't sort the whole array - just the last part of it, so you'd end up with { 2, 7, 8, 3, 9, 0, 1, 4, 5, 6 }. To sort the whole array, just call Arrays.sort(p)
.
Note that the pattern of specifying a range using an inclusive lower bound and an exclusive upper bound is very common in computing, and you should get used to it. Another common example is String.substring
:
String text = "0123456789";
String substring = text.substring(0, 5); // 01234
See more on this question at Stackoverflow