0

I am implementing the median-cut algorithm for an image and I have an ArrayList with all my pixels but now I need to sort it based on one color channel. Here is my Pixel class.

public class Pixel implements Comparable<Pixel>{
    public int x,y;
    public double[] colors;

    public Pixel(int x, int y, double[] colors ){
        this.x=x;
        this.y=y;
        this.colors=colors;
    }

    @Override
    public int compareTo(Pixel compareNode) {
        //not sure what to do here
        return 0;
    }
}

The colors array holds the RGB values in [0], [1], and [2] respectively but when I am overriding the compareTo() method I don't know how I would sort by a specific color channel. Am I just going to have to implement my own sorting method?

Ondrej Slinták
  • 31,386
  • 20
  • 94
  • 126
Alex
  • 9
  • 4
  • 3
    Do you always want to sort Pixels in the same way, or do you want to be able to choose which colour channel to sort by? If you want the latter, you probably want to create some `Comparators`, not implement `Comparable`. – andersschuller Oct 11 '15 at 13:10
  • What does **"I need to sort it based on one color channel"** means? Do you need to sort in a way that all the pixels are sorted first based on RED, then based on GREEN and then by the BLUE? – STaefi Oct 11 '15 at 13:21
  • I need to sort based on the widest color channel. So say the red values go from 2-250, green from 45-180, and blue from 100-200 I would want to sort the entire list with respect to the red channel. – Alex Oct 11 '15 at 13:26
  • Then it is better to create some comparator separately for each channel. Refer to the @triadiktyo answer. – STaefi Oct 11 '15 at 13:31

1 Answers1

2

To sort by a specific channel you can create a Comparator for each color. For example to sort by red values you can use the following example

public static class RedComparator implements Comparator<Pixel> {
    @Override
    public int compare(Pixel p1, Pixel p2) {
        return Double.compare(p1.colors[0], p2.colors[0]);
    }
}

You can then use Collections.sort(yourArrayList, new RedComparator()) to sort your ArrayList by red color.

You can create the other two comparators for green and blue

triadiktyo
  • 479
  • 2
  • 9