Implemented palette sorting for grayscale images