How do I sort items of an array?
Category: java.util, viewed: 1386 time(s).
package org.kodejava.examples.util; import java.util.Arrays; public class ArraySortExample { public static void main(String[] args) { // An array of random numbers int numbers[] = {3, 1, 8, 34, 1, 2, 13, 89, 5, 21, 55}; System.out.print("Before: "); for (int i = 0; i < numbers.length; i++) { int number = numbers[i]; System.out.print(number + "; "); } System.out.println(""); // We need to sort these array elements into a correct // order from the smallest to the greatest. // We will use the Arrays class on java.utils package to do // the sort. The sort method of this class are overloaded, // so they can take other type of array as well such as byte[] // long[], float[], Object[]. Arrays.sort(numbers); System.out.print("After: "); for (int i = 0; i < numbers.length; i++) { int number = numbers[i]; System.out.print(number + "; "); } System.out.println(""); // We can also do the sort only for the specified range of // array elements. float money[] = {1.05f, 99.8f, 3f, 4.55f, 7.23f, 6.50f}; Arrays.sort(money, 3, money.length); // Here we display the sort result, the first and the second // element of the array is not included in the sort process. for (int i = 0; i < money.length; i++) { float v = money[i]; System.out.print(v + "; "); } } } |
Can't find what you are looking for? Join our FORUMS and ask some questions!
Related Examples
- How do I convert LinkedList to array?
- How do I get all available timezones?
- How do I get currency symbol?
- How do I sort items in a Set?
- How do I sort items of an ArrayList?
- How do I sort array values in case insensitive order?
- How do I sort array values in descending order?
- How do I convert milliseconds value to date?
- How do I split a string using Scanner class?
- How do I read file using Scanner class?
- How do I read / write data in Windows registry?
- How do I read user input from console using Scanner class?
- How do I use ResourceBundle for i18n?
- How do I convert time between timezone?
- How do I set a default Locale?
- How do I remove duplicate element from array?
- How do I convert array to Set?
- How do I use the HashMap class?
- How do I generate a random array of numbers?
- How do I create a queue using LinkedList class?
Most Viewed Examples
Latest Code Examples
Categories
100 Top & Latest
Latest Jobs
Blog Entries
Forums Entries
- Google Chrome
- Re: Importing and scanning the text
- Re: What Java books have you read?
- Re: How to create exe file
- How to create exe file
- Re: What Java books have you read?
- Infix expression
- Importing and scanning the text
- Re: I want to reduce the size of a JPG image
- MOVED: I want to reduce the size of a JPG image
