Monday, January 7, 2008

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

Labels: ,

1 Comments:

At February 13, 2008 9:46 AM , Blogger 7khat said...

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

 

Post a Comment

<< Home