Such code, however, is flawed. For instance, when swapping triangles it doesn't swaps the triangle areas as well. Moreover it performs truncating operations (division and sqare root) on integers.

Try

C

#include <stdio.h> #include <stdlib.h> #include <math.h> typedef struct Triangle { unsigned a; unsigned b; unsigned c; } Triangle; // compute (4 * squared area) of a triangle // this way division and square root are avoided while ordering is maintained unsigned fts_area(Triangle * t) { unsigned p = t->a + t->b + t->c; // perimeter unsigned fts = p * ( p - 2* t->a) * (p - 2 * t->b) * (p - 2 * t->c); // 4 times the squared area return fts; } void sort_by_area(Triangle tr[], unsigned n) { unsigned * a = (unsigned *) malloc(n * sizeof(unsigned)); if (! a ) return; // todo: print an error message for (unsigned i=0; i<n; ++i) { a[i] = fts_area(&tr[i]); } for( unsigned i=0; i<n-1; ++i) { for (unsigned j=0; j<(n-i)-1; ++j) { if(a[j] > a[j+1]) { Triangle temp_tr = tr[j]; // swap the triangles tr[j] = tr[j+1]; tr[j+1] = temp_tr; unsigned temp_a = a[j]; // swap their 'areas' as well a[j] = a[j+1]; a[j+1] = temp_a; } } } free(a); } #define TRIANGLES 4 int main() { Triangle tr[TRIANGLES] = { {2,3,4}, { 100, 42, 80}, { 10, 11, 15}, { 2,2, 3}}; sort_by_area( tr, TRIANGLES); for ( unsigned n = 0; n < TRIANGLES; ++n) { double area = sqrt(fts_area(&tr[n])) / 4; printf("{ %u , %u, %u }, %g\n", tr[n].a, tr[n].b, tr[n].c, area); } }