Examples of java array descending and ascending order

Source: Internet
Author: User
Tags arrays function prototype sorts


The java. util. Arrays class provides several static methods for sorting Arrays. For example, use Arrays. sort (), input the array as a parameter, and return the sorted array. In java, we can also use ascending or descending or custom comparator for sorting.

Sort java arrays in ascending order

Sort Arrays (String, int, and other types) in ascending order. We can directly use Arrays. the sort () method, which is sorted in ascending order by default based on the natural order (natral order) implemented by the CompareTo method. The so-called natural order. For example, for the String type, sort by alphabet and for the integer type, sort by number size. We can also use this method to sort anonymous arrays, but this does not actually mean anything.

Sort java arrays in descending order

To sort java arrays in descending order, you need to provide an external Comparator
To sort the elements in reverse order. However, java APIs provide such java. util. Collections. reverseOrder () method. This method returns a comparator that is in the opposite order of nature. This comparator is passed as a parameter to the sort method to implement descending order. Of course, you can also convert the array to ArrayList first, then call the reverse () method of ArrayList, and then convert it to an array. However, it is best to use the Arrays. sort () method.

Sort sub-arrays in the java array

The Arrays class provides a method to sort partial elements of an array. For example, you may have many arrays, and you only need to sort specific segments, you can use java. util. arrays. sort (array, index, index), which sorts only the elements in the specified range. This is faster than sorting the entire array.

The complete code is provided below:

Import java. util. Arrays;
Import java. util. Collections;
 
Public class HashtableDemo {
 
Public static void main (String args []) {
String [] companies = {"Google", "Apple", "Sony "};
 
// Sorting java array in ascending order
System. out. println ("Sorting String Array in Ascending order in Java Example ");
System. out. println ("Unsorted String Array in Java :");
PrintNumbers (companies );
Arrays. sort (companies );
System. out. println ("Sorted String Array in ascending order :");
PrintNumbers (companies );
 
// Sorting java array in descending order
System. out. println ("Sorting Array in Descending order in Java Example ");
System. out. println ("Unsorted int Array in Java :");
PrintNumbers (companies );
Arrays. sort (companies, Collections. reverseOrder ());
System. out. println ("Sorted int Array in descending order :");
PrintNumbers (companies );
 
System. out. println ("Sorting part of array in java :");
Int [] numbers = {1, 3, 2, 5, 4 };
Arrays. sort (numbers, 0, 3 );
System. out. println ("Sorted sub array in Java :");
For (int num: numbers ){
System. out. println (num );
}
 
}
 
Public static void printNumbers (String [] companies ){
For (String company: companies ){
System. out. println (company );
}
}
 
}
 
Output:
Sorting String Array in Ascending order in Java Example
Unsorted String Array in Java:
Google
Apple
Sony
 
Sorted String Array in ascending order:
Apple
Google
Sony
 
Sorting Array in Descending order in Java Example
Unsorted int Array in Java:
Apple
Google
Sony
Sorted String Array in descending order:
Sony
Google
Apple
Sorting part of array in java:
Sorted sub array in Java:

1
2
3
5
4
 
Important points about the Arrays. sort () method:

1. Arrays. sort () is an overloaded method. You can sort the int, byte, short, char, or the Object [] array.
2. Arrays. sort () can also be sorted by sub-Arrays of Arrays.
3. The Arrays class also provides other tool methods, such as binarySearch half-lookup to search for Arrays.

Example

Sort the array in ascending order by default.

Function prototype: static void sort (int [] a) sorts the specified int array in ascending order of numbers.

Static void sort (int [] a, int fromIndex, int toIndex) sorts the specified range of a specified int array in ascending order of numbers.

Code example:


Import java. util. Arrays;
Public class ArraysSort_11 {
Public static void main (String args [])
    {
Int [] a = {,-, 0 };
Arrays. sort ();
// The content of array a [] is changed to {-, 5}
For (int I = 0; I <a. length; I ++)
System. out. print (a [I] + "");
    }
}

2. Sort data of the composite data type

Function prototype: (1) public static <T> void sort (T [] a, Comparator c) sorts the array of specified objects according to the sequence generated by the specified Comparator.

(2) public static <T> void sort (T [] a, int fromIndex, int toIndex, Comparator c) sorts the specified range of the specified object array based on the generation sequence of the specified comparator.

Note: These two sorting algorithms are the "optimized merge sorting" algorithms.

Code example:


Package aa;

Import java. util. Arrays;
Import java. util. Comparator;

Public class Arraysort {
Point [] arr;
   
Arraysort (){
Arr = new Point [4]; // defines an array of objects, arr, and allocates storage space.
For (int I = 0; I <4; I ++)
Arr [I] = new Point ();
    }
   
Public static void main (String [] args ){
       
Arraysort sort = new Arraysort ();
Sort. arr [0]. x = 2; sort. arr [0]. y = 1; // initialization, data in the object array
Sort. arr [1]. x = 2; sort. arr [1]. y = 2;
Sort. arr [2]. x = 1; sort. arr [2]. y = 2;
Sort. arr [3]. x = 0; sort. arr [3]. y = 1;
 
Arrays. sort (sort. arr, new MyComprator (); // use the specified sorter for sorting.
For (int I = 0; I <4; I ++) // output the sorting result
System. out. println ("(" + sort. arr [I]. x + "," + sort. arr [I]. y + ")");
    }
}

Class Point {
Int x;
Int y;
}

// Comparator. The x coordinates are sorted in ascending order. The x coordinates are sorted in ascending order by y at the same time.
Class MyComprator implements Comparator {
Public int compare (Object arg0, Object arg1 ){
Point t1 = (Point) arg0;
Point t2 = (Point) arg1;
If (t1.x! = T2.x)
Return t1.x> t2.x? 1:-1;
Else
Return t1.y> t2.y? 1:-1;
    }
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.