tag “array”
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 no comment
recent posts
- › how to use phing to build php projects
- › slice/paging large contents using php
- › how to log methods call in php ?
- › sql IN logical operation for java
- › backup from mysql database's routines
- › how to deploy war file into web root ?
- › how to get all oracle components version ?
- › temporary/memory tables in mysql
- › Set JFreeChart data from database
- › How to search and sort primitive arrays in Java ?
archive
- › 2011/06 (1)
- › 2010/11 (1)
- › 2010/10 (1)
- › 2009/04 (2)
- › 2008/05 (1)
- › 2008/03 (1)
- › 2008/01 (4)
- › 2007/12 (4)
last tweet
- ›