Close

Java Collections - Arrays.sort() Examples

Code Snippets Java Collections Java Java API 


Class:

java.util.Arrays

java.lang.Objectjava.lang.Objectjava.util.Arraysjava.util.ArraysLogicBig

Methods:

These methods sort the specified array into natural order or in an order provided by the specified comparator.

public static void sort(int[] a)
public static void sort(int[] a,
                        int fromIndex,
                        int toIndex)
public static void sort(long[] a)
public static void sort(long[] a,
                        int fromIndex,
                        int toIndex)
public static void sort(short[] a)
public static void sort(short[] a,
                        int fromIndex,
                        int toIndex)
public static void sort(char[] a)
public static void sort(char[] a,
                        int fromIndex,
                        int toIndex)
public static void sort(byte[] a)
public static void sort(byte[] a,
                        int fromIndex,
                        int toIndex)
public static void sort(float[] a)
public static void sort(float[] a,
                        int fromIndex,
                        int toIndex)
public static void sort(double[] a)
public static void sort(double[] a,
                        int fromIndex,
                        int toIndex)
public static void sort(Object[] a)
public static void sort(Object[] a,
                        int fromIndex,
                        int toIndex)
public static <T> void sort(T[] a,
                            Comparator<? super T> c)
public static <T> void sort(T[] a,
                            int fromIndex,
                            int toIndex,
                            Comparator<? super T> c)

Examples


package com.logicbig.example.arrays;

import java.util.Arrays;

public class SortExample {

public static void main(String... args) {
int[] arr = {8, 9, 4, 3, 6, 7, 0, 8, 7, 5, 1};
Arrays.sort(arr);
System.out.println(Arrays.toString(arr));
}
}

Output

[0, 1, 3, 4, 5, 6, 7, 7, 8, 8, 9]




package com.logicbig.example.arrays;

import java.util.Arrays;

public class SortExample2 {

public static void main(String... args) {
int[] arr = {8, 9, 4, 3, 6, 7, 0, 8, 7, 5, 1};
System.out.println(Arrays.toString(arr));

Arrays.sort(arr, 0, 5);
System.out.println(Arrays.toString(arr));
}
}

Output

[8, 9, 4, 3, 6, 7, 0, 8, 7, 5, 1]
[3, 4, 6, 8, 9, 7, 0, 8, 7, 5, 1]




package com.logicbig.example.arrays;

import java.util.Arrays;
import java.util.Comparator;

public class SortExample3 {

public static void main(String... args) {
Integer[] arr = {8, 9, 4, 3, 6, 7, 0, 8, 7, 5, 1};
System.out.println(Arrays.toString(arr));

Arrays.sort(arr, Comparator.reverseOrder());
System.out.println(Arrays.toString(arr));
}
}

Output

[8, 9, 4, 3, 6, 7, 0, 8, 7, 5, 1]
[9, 8, 8, 7, 7, 6, 5, 4, 3, 1, 0]




See Also