简体   繁体   English

快速排序多维数组

[英]quick sort on multidimensional array

Edit: I want this method to sort in ascending order based on any column the user want (each data in the same respective row is 'attached' to each other). 编辑:我希望此方法根据用户想要的任何列按升序排序(相同的相应行中的每个数据彼此“附加”)。 There are 4 column in the table. 表中有4列。 if the user want to sort in based on first column then he should do something like 如果用户想要根据第一列进行排序,那么他应该做类似的事情

mySortedTable[][] = ClassName.quickSort(myUnsortedTable,0); 

As you can see I tried to code what my title said. 正如你所看到的,我试着编写我的标题所说的代码。 For some reason our data table is organized in a 2d Array of Strings(which is NOT handy, had to convert back and forth to implement ArrayList). 由于某种原因,我们的数据表被组织在一个2d字符串数组中(这不是很方便,必须来回转换才能实现ArrayList)。 I used the first data as the pivot. 我使用第一个数据作为支点。 Mind debugging it together with me? 介意与我一起调试它? :) :)

public static String[][] quickSort(String[][] data,int column) {
    //1st step, create ArrayLists needed and compare the data by the pivot to determine which ArrayList to be filled.
    ArrayList<String[]> hiData = new ArrayList<String[]>();
    ArrayList<String[]> loData = new ArrayList<String[]>();
    ArrayList<String[]> pivots = new ArrayList<String[]>();
    String[] pivot = {data[0][0],data[0][1],data[0][2],data[0][3]};
    for(String[] row : data) {
        if(row[column].compareTo(pivot[column])<0)
            loData.add(row);
        else if (row[column].compareTo(pivot[column])>0)
            hiData.add(row);
        else pivots.add(row);
    }

    //To decide whether is needed to create the array from the ArrayList for recursively sort the parted data.
    if(loData.size()>0) {
        String[][] loDataArr = new String[loData.size()][4];
        for(int i=0;i<loData.size();i++)
            loDataArr[i]=loData.get(i);
        if(loData.size()>1)
            loDataArr = quickSort(loDataArr,column);
    }
    if(hiData.size()>0) {   
        String[][] hiDataArr = new String[hiData.size()][4];
        for(int i=0;i<hiData.size();i++)
            hiDataArr[i]=hiData.get(i);
        if(hiData.size()>1)
            hiDataArr = quickSort(hiDataArr,column);
    }

    //Combine parted data into new array and return it to feed the recursive back up until the first recursive call.
    String result[][] = new String[hiData.size()+loData.size()+pivots.size()][4];
    int j=0;
    for(String[] row : loData) {
        result[j]=row;
        j++;
    }
    for(String[] row : pivots) {
        result[j]=row;
        j++;
    }
    for(String[] row : hiData) {
        result[j]=row;
        j++;
    }
    return result;
}

It outputs all the arrays, but is not sorted and also not equals with the arrays it started with. 它输出所有数组,但没有排序,也不与它开始的数组相等。 Also side question, I want to ask if ArrayList<String[]> do NOT smells bad, or is it? 另外一个问题,我想问一下ArrayList<String[]>是不是闻起来不好,或者是吗?

In Java, arrays are always one dimensional - although their element type may be an array itself. 在Java中,数组总是一维的 - 尽管它们的元素类型可能是数组本身。 So a two dimensional array in Java is just an array of arrays. 所以Java中的二维数组只是一个数组数组。

This fact becomes very handy when you want to sort an array so that rows stick together. 当您想要对数组进行排序以使行粘在一起时,这个事实变得非常方便。 You treat each row as an object, and use a comparator to compare the object. 您将每一行视为一个对象,并使用比较器来比较该对象。

Here is a little demonstration: 这是一个小小的示范:

public class SortDemonstration {

    public static void main(String[] args) {

        String[][] table = {
                {"The", "Quick",  "Brown"},
                {"Fox", "Jumped", "Over"},
                {"A",   "Lazy",   "Dog"}
            };

        Arrays.sort( table, new ColumnComparator(0));
        System.out.println( Arrays.deepToString(table));

        Arrays.sort( table, new ColumnComparator(1));
        System.out.println( Arrays.deepToString(table));

        Arrays.sort( table, new ColumnComparator(2));
        System.out.println( Arrays.deepToString(table));
    }

    private static class ColumnComparator implements Comparator<String []>{
        private final int index;
        public ColumnComparator(int index) {
            this.index = index;
        }
        @Override
        public int compare(String[] o1, String[] o2) {
            return o1[index].compareTo(o2[index]);
        }

    }

}

The ColumnComparator class is the key to the solution. ColumnComparator类是解决方案的关键。 It implements a comparator of two string arrays (two rows). 它实现了两个字符串数组(两行)的比较器。 It compares the rows based on the item at the index it was instantiated with. 它根据实例化的索引处的项目比较行。

Thus a new ColumnComparator(0) compares two rows based on the first column. 因此, new ColumnComparator(0)基于第一列比较两行。 A new ColumnComparator(1) compares two rows based on the second column, etc. new ColumnComparator(1)根据第二列等比较两行。

Now that you have this comparator class, you can sort an array of "rows" using it. 现在你有了这个比较器类,你可以使用它对一系列“行”进行排序。 The output from this program is: 该程序的输出是:

[[A, Lazy, Dog], [Fox, Jumped, Over], [The, Quick, Brown]]
[[Fox, Jumped, Over], [A, Lazy, Dog], [The, Quick, Brown]]
[[The, Quick, Brown], [A, Lazy, Dog], [Fox, Jumped, Over]]

I found the problem in my code. 我在代码中发现了问题。 I built the parted data using the unsorted ArrayList instead of the sorted 2 dimensional array. 我使用未排序的ArrayList而不是排序的2维数组构建了分离数据。

//Second step... 
        String[][] loDataArr = new String[loData.size()][4];
        String[][] hiDataArr = new String[hiData.size()][4];
        if(loData.size()>0) {
            for(int i=0;i<loData.size();i++)
                loDataArr[i]=loData.get(i);
            if(loData.size()>1)
                loDataArr = quickSort(loDataArr,column);
        }
        if(hiData.size()>0) {   
            for(int i=0;i<hiData.size();i++)
                hiDataArr[i]=hiData.get(i);
            if(hiData.size()>1)
                hiDataArr = quickSort(hiDataArr,column);
        }
        String result[][] = new String[hiData.size()+loData.size()+pivots.size()][4];
        int j=0;
        for(String[] row : loDataArr) {
            result[j]=row;
            j++;
        }
        for(String[] row : pivots) {
            result[j]=row;
            j++;
        }
        for(String[] row : hiDataArr) {
            result[j]=row;
            j++;
        }
        return result;
    }

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM