Listing 2

/*begin************************************************
*   Program   : sort_color
*   Descript. : Sorts the palette by the red color only
*               Also builds the index array
*               for fast lookup.
*end**************************************************/

void sort_color()
{
int i;
int j;

/*  Make a copy of the original palette */
for ( i=0; i<PAL_LEN; i++ )
    {
    pals[ i ].num = i;
    pals[ i ].red = palo[ i ].red;
    pals[ i ].grn = palo[ i ].grn;
    pals[ i ].blu = palo[ i ].blu;
    }

/* Sort the copy of the palette */
qsort( (void *)pals, PAL_LEN, sizeof(pal), color_comp);

/* build the quick index    */
/* so we don't have to do a */
/* binary search every time */

for ( i=0, j=0; i<PAL_LEN; i++ )
    {
    while( pals[ j ].red < i )
       if ( ++j >= PAL_LEN )
          {
          j = PAL_LEN - 1;
          break;
          }
    redindex[ i ] = j;
    }
}


/*begin*************************************************
*   Program    : color_comp
*    Descript. : Compares two colors (red) in a palette.
*end***************************************************/

int color_comp( const void *a, const void *b )
{
pal *aa;
pal *bb;

aa = (pal *)a;
bb = (pal *)b;
return( aa->red - bb->red );
}

/* End of File */