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就像一个容器,可以容纳固定数量的相同类型的项目,它可以是原始类型也可以是对象。

Java中的数组排序 (Array Sorting in Java)

Sometimes we need to sort array in java, we can use Arrays class to sort the array. Arrays is a utility class that provides a lot of useful methods to work with arrays in java.

有时我们需要在java中对数组进行排序 ,我们可以使用Arrays类对数组进行排序。 数组是一个实用程序类,提供了许多有用的方法来使用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]
Array Sorting In Java

Array Sorting In Java

Java中的数组排序

重要事项 (Important Points)

  1. We can use Arrays.sort(T[] tArr) only if the array type implements Comparable interface.

    仅当数组类型实现Comparable接口时,才能使用Arrays.sort(T[] tArr)
  2. There is another variant of 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)还有另一个变体,我们可以使用它根据不同的字段对自定义对象数组进行排序。
  3. You can head over to java comparable and comparator to learn about sorting an array using Comparator.

    您可以转到Java可比较器和比较器,以了解使用Comparator对数组进行排序的知识。
  4. 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)) 。 排序以自然升序进行。

用Java对数组进行排序有哪些不同的方法? (What are different ways to sort an array in Java?)

There are many algorithms to sort an array. Some of the popular ones are:

有很多算法可以对数组进行排序。 一些受欢迎的是:

  1. Bubble Sort

    气泡排序
  2. Insertion Sort

    插入排序
  3. Heap Sort

    堆排序
  4. Merge Sort

    合并排序
  5. Quick Sort

    快速排序

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()函数以实现无错误的排序和快速的性能。

翻译自: https://www.journaldev.com/784/sort-array-java

java中对数组进行排序

Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐