How to search and sort primitive arrays in Java ?

by Hamid Reza Fahimi Madjd @ Jan 8, 2008

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"};
Arrays.sort(test);
System.out.println(Arrays.toString(test));

The result will be:

[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);
System.out.println(Arrays.toString(test));
System.out.println(Arrays.binarySearch(test, "a"));

The result will be:

[a, d, z]
1

1 is index of found key otherwise it will be a less than zero number.

Attention: that before using Arrays.binarySearch(aPrimitiveArray, key) method you have to sort array by Arrays.sort(aPrimitiveArray) method.

array, java

1 comment

#1. 7khat @ 2008-02-13 09:46:00

چرا دیر به دیر می نویسی؟
راستی به لیست دوستان وبلاگم اضافت کردم
پاینده باشی.
من هم اول راه در جاوا هستم

last tweet