本文共 2322 字,大约阅读时间需要 7 分钟。
java中对数组进行排序
Java Array is like a container that can hold a fixed number of the same type of items, it can be primitive types as well as Objects.
Java Array就像一个容器,可以容纳固定数量的相同类型的项目,它可以是原始类型也可以是对象。
Sometimes we need to sort array in java, we can use class to sort the array. Arrays is a utility class that provides a lot of useful methods to work with arrays in java.
有时我们需要在java中对数组进行排序 ,我们可以使用类对进行排序。 数组是一个实用程序类,提供了许多有用的方法来使用Java中的数组。
Let’s look at an example to sort an array in Java.
让我们看一个在Java中对数组排序的示例。
package com.journaldev.sort;import java.util.Arrays;public class JavaArraySort { /** * This class shows how to sort an array in Java * @param args */ public static void main(String[] args) { int[] intArr = {1, 4, 2, 6, 3}; String[] strArr = {"E", "A", "U","O","I"}; //sort int array Arrays.sort(intArr); Arrays.sort(strArr); System.out.println(Arrays.toString(intArr)); System.out.println(Arrays.toString(strArr)); }}
Output of the above program is:
上面程序的输出是:
[1, 2, 3, 4, 6][A, E, I, O, U]
Arrays.sort(T[] tArr)
only if the array type implements Comparable interface. 仅当数组类型实现Comparable接口时,才能使用Arrays.sort(T[] tArr)
。 Arrays.sort(T[] tArr, Comparator c)
that we can use to sort custom object array based on different fields. Arrays.sort(T[] tArr, Comparator c)
还有另一个变体,我们可以使用它根据不同的字段对自定义对象数组进行排序。 Arrays.sort(T[] t)
uses Dual-Pivot Quicksort algorithm with performance of O(n log(n)). The sorting is done in natural ascending order. Arrays.sort(T[] t)
使用Dual-Pivot Quicksort算法 ,性能为O(n log(n)) 。 排序以自然升序进行。 There are many algorithms to sort an array. Some of the popular ones are:
有很多算法可以对数组进行排序。 一些受欢迎的是:
We can write code to implement any of these algorithms to sort an array. However, it’s always recommended to use built-in Arrays.sort() function for error-free sorting and fast performance.
我们可以编写代码来实现所有这些算法来对数组进行排序。 但是,始终建议使用内置的Arrays.sort()函数以实现无错误的排序和快速的性能。
翻译自:
java中对数组进行排序
转载地址:http://vmozd.baihongyu.com/