Code Bloat, or Are Bundled Commands More Efficient?

Sometimes I'm bad at looking things up and end up doing things like writing my own code to sort an array. Is there a way to figure out how a bundled command, like sort(list), works? are these shortcuts more efficient than writing out the code? It doesn't seem like it would be, unless you write code like me. For your amusement, here's code I wrote to sort a color array by brightness:

color []pixB = new color [16]; //pre-defined by transformation of an imported jpg
color []colFin = new color [16];

void colorSort(){
  for (int z = 0; z < 16; z++){
    for (int a = 0; a < 16; a++){
      if (z == 0){
        if (a == 0){
          colFin[z] = pixB[a];
        }
        else if ((brightness(pixB[a]) <= brightness(colFin[z])) && (brightness(pixB[a]) < brightness(pixB[a-1]))){
          colFin[z] = pixB[a];
        }
      }
      if (z > 0){
        if (a == 0){
          if (brightness(pixB[a]) > brightness(colFin[z-1])){
            colFin[z] = pixB[a];
          } else {
              colFin[z] = color(0, 0, 255);
            }
        }
        else if ((brightness(pixB[a]) <= brightness(colFin[z])) && (brightness(pixB[a]) > brightness(colFin[z-1]))){
          for (int h = 0; h < a; h++){
            if (pixB[a] != colFin[h]){
              colFin[z] = pixB[a]; 
            }
          }
        }
      } 
    }
    output.println(z + ": r" + red(colFin[z]) + ", g" + green(colFin[z]) + ", b" + blue(colFin[z]));
  }
}

Actually, can this be done with the sort() command?

Answers

  • edited March 2014

    Processing's own sort() function is very limited! Only String[] and some primitives like byte[], char[], int[], float[]! :-<
    Nevertheless, I'd love Processing offering shuffle() for arrays as well! 8->

    In order to accept any array data-type, we gotta use java.util.Arrays.sort().
    Although w/ an important condition: it gotta implement Comparable interface w/ compareTo() method! :-SS
    Inside that, it gotta return either [-1, 0, 1], depending if a value compared to another is lesser, equal or greater.

    I've got a good example about a Card class, which is sorted by rank & suit, in the thread below:

    forum.processing.org/two/discussion/2801/picking-cards-at-random-then-excluding-those-from-further-picking-

    In your case, I believe you're gonna need a Colour class w/ separate RGB and brightness fields.
    I believe you wanna sort colors by their brightness, right? :-/

    I've got an example of a Colour class in the thread below. However, it sorts out by color names. You're gonna need lotsa tweaks!

    forum.processing.org/two/discussion/1273/what-is-the-triple_dot-character-and-what-causes-errors-regarding-it

  • Well, what I wrote definitely works, and I can punch in any numbers I want. I could even throw some variables in to make it easy to change the numbers.

    I'm just wondering if I'm hogging memory by writing it out.

Sign In or Register to comment.