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

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:

System.out.println(Arrays.binarySearch(test, "a"));

The result will be:

[a, d, z]

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

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

add your comment

name (required)
email (required)

not readable? sorry, click here

last tweet

Developed withDeveloped with