How to search and sort primitive arrays in Java ?
Always I was keen on solution for sorting and searching primitive arrays. Today I found java.util.Arrays class that includes some useful static methods for sorting, searching, filling and ... For sorting you can use Arrays.sort(aPrimitiveArray) static method, look here :
String[] test = {"d", "z", "a"};The result will be:
Arrays.sort(test);
System.out.println(Arrays.toString(test));
[a, d, z]As you see we've used Arrays.toString(test) for printing sorted array.
And for searching you can use Arrays.binarySearch(aPrimitiveArray, key) static method:
Arrays.sort(test);The result will be:
System.out.println(Arrays.toString(test));
System.out.println(Arrays.binarySearch(test, "a"));
[a, d, z]1 is index of found key otherwise it will be a less than zero number.
1
Attention: that before using Arrays.binarySearch(aPrimitiveArray, key) method you have to sort array by Arrays.sort(aPrimitiveArray) method.
