简体   繁体   English

java Arrays.sort 二维数组

[英]java Arrays.sort 2d array

I am looking to sort the following array based on the values of [][0]我希望根据 [][0] 的值对以下数组进行排序

double[][] myArr = new double[mySize][2];

so for example, myArr contents is:例如,myArr 内容是:

1      5
13     1.55
12     100.6
12.1   .85

I want it to get to:我希望它达到:

1      5
12     100.6
12.1   .85
13     1.55

I am looking to do this without having to implement my own sort.我希望在不必实现自己的排序的情况下做到这一点。

Use Overloaded Arrays#Sort(T[] a, Comparator c) which takes Comparator as the second argument.使用 Overloaded Arrays#Sort(T[] a, Comparator c) ,它将 Comparator 作为第二个参数。

double[][] array= {
{1, 5},
{13, 1.55},
{12, 100.6},
{12.1, .85} };

java.util.Arrays.sort(array, new java.util.Comparator<double[]>() {
    public int compare(double[] a, double[] b) {
        return Double.compare(a[0], b[0]);
    }
});

JAVA-8: Instead of that big comparator, we can use lambda function as following- JAVA-8:我们可以使用 lambda 函数来代替那个大比较器,如下所示-

Arrays.sort(array, Comparator.comparingDouble(o -> o[0]));

欢迎使用 Java 8:

Arrays.sort(myArr, (a, b) -> Double.compare(a[0], b[0]));

最简单的方法:

Arrays.sort(myArr, (a, b) -> a[0] - b[0]);

Decreasing/increasing order for an integer array of 2 dimension you can use:您可以使用的二维整数数组的递减/递增顺序:

Arrays.sort(contests, (a, b) -> Integer.compare(b[0],a[0])); //decreasing order
    
Arrays.sort(contests, (a, b) -> Integer.compare(a[0],b[0]); //increasing order

You need to implement a Comparator<Double[]> like so:您需要像这样实现Comparator<Double[]>

public static void main(String[] args) throws IOException {
    final Double[][] doubles = new Double[][]{{5.0, 4.0}, {1.0, 1.0}, {4.0, 6.0}};
    final Comparator<Double[]> arrayComparator = new Comparator<Double[]>() {
        @Override
        public int compare(Double[] o1, Double[] o2) {
            return o1[0].compareTo(o2[0]);
        }
    };
    Arrays.sort(doubles, arrayComparator);
    for (final Double[] arr : doubles) {
        System.out.println(Arrays.toString(arr));
    }
}

Output:输出:

[1.0, 1.0]
[4.0, 6.0]
[5.0, 4.0]

Although this is an old thread, here are two examples for solving the problem in Java8.虽然这是一个旧线程,但这里有两个用于解决 Java8 问题的示例。

sorting by the first column ([][0]):按第一列 ([][0]) 排序:

double[][] myArr = new double[mySize][2];
// ...
java.util.Arrays.sort(myArr, java.util.Comparator.comparingDouble(a -> a[0]));

sorting by the first two columns ([][0], [][1]):按前两列排序 ([][0], [][1]):

double[][] myArr = new double[mySize][2];
// ...
java.util.Arrays.sort(myArr, java.util.Comparator.<double[]>comparingDouble(a -> a[0]).thenComparingDouble(a -> a[1]));

Simplified Java 8简化的 Java 8

IntelliJ suggests to simplify the top answer to the: IntelliJ 建议简化以下问题的最佳答案:

Arrays.sort(queries, Comparator.comparingDouble(a -> a[0]));

To sort in descending order you can flip the two parameters要按降序排序,您可以翻转两个参数

int[][] array= {
    {1, 5},
    {13, 1},
    {12, 100},
    {12, 85} 
};
Arrays.sort(array, (b, a) -> Integer.compare(a[0], b[0]));

Output:输出:

13, 5
12, 100
12, 85
1, 5

It is really simple, there are just some syntax you have to keep in mind.这真的很简单,你只需要记住一些语法。

Arrays.sort(contests, (a, b) -> Integer.compare(a[0],b[0]));//increasing order ---1 Arrays.sort(contests, (a, b) -> Integer.compare(a[0],b[0]));//升序---1

Arrays.sort(contests, (b, a) -> Integer.compare(b[0],a[0]));//increasing order ---2 Arrays.sort(contests, (b, a) -> Integer.compare(b[0],a[0]));//升序---2

Arrays.sort(contests, (a, b) -> Integer.compare(b[0],a[0]));//decreasing order ---3 Arrays.sort(contests, (a, b) -> Integer.compare(b[0],a[0]));//降序---3

Arrays.sort(contests, (b, a) -> Integer.compare(a[0],b[0]));//decreasing order ---4 Arrays.sort(contests, (b, a) -> Integer.compare(a[0],b[0]));//降序---4

If you notice carefully, then it's the change in the order of 'a' and 'b' that affects the result.如果您仔细观察,那么影响结果的是“a”和“b”顺序的变化。 For line 1, the set is of (a,b) and Integer.compare(a[0],b[0]), so it is increasing order.对于第 1 行,集合是 (a,b) 和 Integer.compare(a[0],b[0]),因此它是递增顺序。 Now if we change the order of a and b in any one of them, suppose the set of (a,b) and Integer.compare(b[0],a[0]) as in line 3, we get decreasing order.现在,如果我们改变其中任何一个中 a 和 b 的顺序,假设 (a,b) 和 Integer.compare(b[0],a[0]) 的集合如第 3 行,我们得到降序。

much simpler code:更简单的代码:

import java.util.Arrays;导入 java.util.Arrays; int[][] array = new int[][]; int[][] 数组 = 新的 int[][];

Arrays.sort(array, ( a, b) -> a[1] - b[1]); Arrays.sort(array, (a, b) -> a[1] - b[1]);

import java.util.*;

public class Arrays2
{
    public static void main(String[] args)
    {
        int small, row = 0, col = 0, z;
        int[][] array = new int[5][5];

        Random rand = new Random();
        for(int i = 0; i < array.length; i++)
        {
            for(int j = 0; j < array[i].length; j++)
            {
                array[i][j] = rand.nextInt(100);
                System.out.print(array[i][j] + " ");
            }
            System.out.println();
        }

        System.out.println("\n");


        for(int k = 0; k < array.length; k++)
        {
            for(int p = 0; p < array[k].length; p++)
            {
                small = array[k][p];
                for(int i = k; i < array.length; i++)
                {
                    if(i == k)
                        z = p + 1;
                    else
                        z = 0;
                    for(;z < array[i].length; z++)
                    {
                        if(array[i][z] <= small)
                        {
                            small = array[i][z];
                            row = i;
                            col = z;
                        }
                    }
                }
            array[row][col] = array[k][p];
            array[k][p] = small;
            System.out.print(array[k][p] + " ");
            }
            System.out.println();
        }
    }
}

Good Luck祝你好运

Java 8 is now very common nowadays. Java 8 现在非常普遍。

Arrays.sort(myArr,(double[] a,double[] b)->{
                //here multiple lines of code can be placed
                return a[0]-b[0]; 
            });

You can use your own sort, it is very simple.你可以使用自己的排序,很简单。

int[][] matrix = {
            {2, 1, 3},
            {5, 4, 6},
            {8, 7, 9}
        };

for (int k = 0; k < length; k++) {
        for (int i= 0; i < matrix[k].length; i++) {
            for (int j = 0; j < matrix[k].length; j++) {
                if (matrix[k][i] < matrix[k][j]) {
                    int temp = matrix[k][i];
                    matrix[k][i] = matrix[k][j];
                    matrix[k][j] = temp;
                }
            }
        }
    }

System.out.println(Arrays.deepToString(matrix));

OUTPUT输出

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

There are multiple approaches to do this, Here I'm sharing follow two methods by which it can be achieved.有多种方法可以做到这一点,在这里我分享以下两种可以实现的方法。

  • Using Comparator Arrays.sort : An built-in feature of Java.使用 Comparator Arrays.sort :Java 的内置功能。
  • Using Merge Sort使用合并排序

Using Comparator Arrays.sort : A built-in feature of Java.使用 Comparator Arrays.sort :Java 的内置功能。

import java.util.Arrays;

class Array2D {
    public static void printTwoDimensionArray(int [][] arr) {
        for (int i = 0; i < arr.length; i++) {
            for (int j = 0; j < arr[0].length; j++) {
                System.out.print(arr[i][j] + " ");
            }
            System.out.println("");
        }
    }

    public static void main(String [] args) {
        int [][] arr = {
                            {1, 2},
                            {6, 8},
                            {4, 7},
                            {9, 11},
                            {7, 10},
                            {13, 16},
                            {5, 9},
                            {8, 9},
                            {10, 11}
                        };
        Arrays.sort(arr, (a, b) -> Integer.compare(a[0], b[0]));
        printTwoDimensionArray(arr);
    }
}

Using Merge Sort使用合并排序

import java.util.ArrayList;

class MergeSortComparator {
    
    public static void printSingleDimensionArray(int [] arr) {
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i] + " ");
        }
        System.out.println("");
    }

    public static void printDoublyDimensionArray(int [][] arr) {
       for (int i = 0; i < arr.length; i++) {
           for (int j = 0; j < arr[0].length; j++) {
               System.out.print(arr[i][j] + " ");
           }
           System.out.println("");
       }
    }

    public static void merge(int[][] arr, int start, int mid, int end, int index) {
        int i, j, k;
        int n1 = mid - start + 1;
        int n2 = end - mid;
        int columnLength = arr[0].length;
        int [][] leftSubArray = new int [n1][columnLength];
        int [][] rightSubArray = new int [n1][columnLength];
        
        // Copy elements to Temp LeftSubArray
        for (i = 0; i < n1; i++) {
            for (j = 0; j < columnLength; j++) {
                leftSubArray[i][j] = arr[start + i][j];
            }
        }

        // Copy elements to Temp RightSubArray
        for (i = 0; i < n2; i++) {
            for (j = 0; j < columnLength; j++) {
                rightSubArray[i][j] = arr[mid + 1 + i][j];
            }
        }

        i = j = k = 0;
        while(i < n1 && j < n2) {
            if (leftSubArray[i][index] <= rightSubArray[j][index]) {
                arr[start + k] = leftSubArray[i];
                i++;
            } else {
                arr[start + k] = rightSubArray[j];
                j++;
            }
            k++;
        }
        while(i < n1) {
            arr[start + k] = leftSubArray[i];
            i++;
            k++;
        }
        while(j < n2 && (start + k) < end) {
            arr[start + k] = rightSubArray[j];
            j++;
            k++;
        }
        
    }

    public static void mergeSort(int[][] arr, int start, int end, int index) {
        if (start >= end) {
            return;
        }
        int mid = (start + end) / 2;
        mergeSort(arr, start, mid, index);
        mergeSort(arr, mid + 1, end, index);
        merge(arr, start, mid, end, index);
        return;
    }
    
    public static void main(String [] args) {
        int [][] arr = {
                            {1, 2},
                            {6, 8},
                            {4, 7},
                            {9, 11},
                            {7, 10},
                            {13, 16},
                            {5, 9},
                            {8, 9},
                            {10, 11}
                        };
        
        int m = arr.length;
        int n = arr[0].length;
        // Last argument as Index is set to 0,
        mergeSort(arr, 0, m-1, 0);
        printDoublyDimensionArray(arr);
    }
}

For a general solution you can use the Column Comparator .对于一般解决方案,您可以使用Column Comparator The code to use the class would be:使用该类的代码是:

Arrays.sort(myArr, new ColumnComparator(0));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Java:不按Arrays.sort()按列对2D数组排序 - Java: Sorting a 2D Array by Columns without Arrays.sort() 不使用 Arrays.sort() 对二维数组进行排序 - Sort 2D array without using Arrays.sort() 如何使用 Arrays.sort 方法对 Java 中的二维 integer 数组进行排序 - How to use Arrays.sort method to sort a 2D integer array in Java 如何使用Arrays.sort对Java 2d字符串数组中的每一行进行排序? - How to sort each row in a 2d String array in java using Arrays.sort? Java使用Arrays.sort()排序2d talble错误 - Java sorting 2d talble error with Arrays.sort() 了解 Java 使用 Arrays.sort() 对二维数组进行排序 - Understanding Java Sorting a 2D-Array using Arrays.sort() Java Arrays.sort()方法需要一维数组,但我也可以传递一个二维数组,那为什么我不能做int [] a = b(其中b是一个二维数组)? - Java Arrays.sort() method takes 1D arrays, but I can pass a 2D array as well then why can't I do int[] a=b(where b is a 2D array)? 为什么 Arrays.sort(T[] a, 比较器<!--? super T--> c) 将 T 推断为二维数组的 Object? - Why Arrays.sort(T[] a, Comparator<? super T> c) infers T as Object for a 2d array? 二维整数数组失败的Arrays.sort - Arrays.sort for 2-D Integer Array failing Java:不使用Arrays.sort()对整数数组进行排序 - Java : Sort integer array without using Arrays.sort()
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM