LoginSignup
4
7

More than 5 years have passed since last update.

processingで2次元配列をソート

Last updated at Posted at 2015-10-22

Processingで1次元配列をソートする関数は用意されているのですが、
2次元配列の2次元目のデータでソートしたかったのでちょっと調べてみました。

Comparatorインターフェースを実装したクラスを作って(その際、2次元目の
どのインデックスでソートするかを指定)、そのオブジェクトと元の配列を
Arrays.sort()に渡せばソートされました。


import java.util.*;

int[][] num = new int[10][2];

void setup () {

    size (400, 400);

    num[0][0] = 5;
    num[1][0] = 8;
    num[2][0] = 1;
    num[3][0] = 3;
    num[4][0] = 9;
    num[5][0] = 7;
    num[6][0] = 6;
    num[7][0] = 2;
    num[8][0] = 4;
    num[9][0] = 10;

    num[0][1] = 10;
    num[1][1] = 4;
    num[2][1] = 6;
    num[3][1] = 8;
    num[4][1] = 5;
    num[5][1] = 2;
    num[6][1] = 7;
    num[7][1] = 3;
    num[8][1] = 1;
    num[9][1] = 9;


    for (int i = 0; i < num.length; i++) {
        println (num[i][0], num[i][1]);
    }

    //Comparatorインターフェイスを実装したクラスを作成
    Comp comp = new Comp ();

    //2次元目のインデックス0番でソート
    comp.set_index (0);
    //Arraysクラスのsort()を実行する
    Arrays.sort (num, comp);
    //ソート後のデータを出力
    for (int i = 0; i < num.length; i++) {
        println (num[i][0], num[i][1]);
    }

    //2次元目のインデックス1番でソート
    comp.set_index (1);
    //Arraysクラスのsort()を実行する
    Arrays.sort (num, comp);
    //ソート後のデータを出力
    for (int i = 0; i < num.length; i++) {
        println (num[i][0], num[i][1]);
    }

}

void draw () {
}

class Comp implements Comparator {

    int index = 0;

    void set_index (int i) {
        index = i;
    }

    int compare (Object a, Object b) {
        int[] int_a = (int[]) a;
        int[] int_b = (int[]) b;
        return (int_a[index] - int_b[index]);
    }

}

4
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
7