Java 實現二維數組按指定列經行排序

來源:互聯網
上載者:User
import java.util.*;    public static void sortIntArray(int[][] arObjects, final int[] arOrders)    {        Arrays.sort(arObjects, new Comparator<Object>()        {            public int compare(Object oObjectA, Object oObjectB)            {                int[] arTempOne = (int[])oObjectA;                int[] arTempTwo = (int[])oObjectB;                for (int i = 0; i < arOrders.length; i++)                {                    int k = arOrders[i];                    if (arTempOne[k] > arTempTwo[k])                    {                        return 1;                    }                    else if (arTempOne[k] < arTempTwo[k])                    {                        return -1;                    }                    else                    {                        continue;                    }                }                return 0;            }        });    }

調用方法是:

    public static void main(String[] args)    {        int array[][] = new int[][] {                     { 12, 34, 68, 32, 9, 12, 545 },                     { 34, 72, 82, 57, 56, 0, 213 },                     { 12, 34, 68, 32, 21, 945, 23 },                     { 91, 10, 3, 2354, 73, 34, 18 },                    { 12, 83, 189, 26, 27, 98, 33 },                     { 47, 23, 889, 24, 899, 23, 657 },                     { 12, 34, 68, 343, 878, 235, 768 },                     { 12, 34, 98, 56, 78, 12, 546 },                     { 26, 78, 2365, 78, 34, 256, 873 } };            sortIntArray(int[][], int[])(array, new int[] { 0, 1 });    // 先根據第一列比較,若相同則再比較第二列        for (int i = 0; i < array.length; i++)        {            for (int j = 0; j < array[i].length; j++)            {                System.out.print(array[i][j]);                System.out.print("\t");            }            System.out.println();        }    }

註:本文轉載自:http://blog.sina.com.cn/s/blog_5a15b7d101014ngm.html

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.