Sorting triangles by materials and textures?

I’m trying to write an export script to use with my C program. For optimization purposes (to reduce the number of times a material or texture is changed) I need to sort triangles by both Materials and Textures. It would be best if these triangles could be organized into groups.

Groups example:
tri[0][15] #triangle 15 in group 0

Sorting example:
group1: tex1 mat1
group2: tex1 mat2
group3: tex2 mat1
group4: tex2 mat3
group5: tex3 mat2

I want the textures to change less often then the materials (I am not sure if binding textures is slower than changing material properties, but I’m assuming it is.)

Does anybody have any idea as to how this could be done? I’ve sorted by textures before, and I’ve sorted by materials before, but the methods I used seem incompatable. I don’t know any good way of doing this.