C program to sort triangles based on area

CServer Side ProgrammingProgramming

Suppose we have an array of different triangles where triangles[i] = [ai, bi, ci] these are the sides of ith triangle. We shall have to sort the triangles based on their area. The area of a triangle by using sides is: square root of p*(p-a)*(p-b)*(p-c) where p = (a+b+c)/2.

So, if the input is like (7, 24, 25), (5, 12, 13), (3, 4, 5), then the output will be (3, 4, 5), (5, 12, 13), (7, 24, 25)

To solve this, we will follow these steps −

  • Define triangle object with sides a, b and c
  • Define a function square(), this will take Triangle t,
  • a := t.a
  • b := t.b
  • c := t.c
  • return (a + b + c) * (a + b - c) * (a - b + c) * (-a + b + c)
  • From the main method, do the following:
  • for initialize i := 0, when i < N, update (increase i by 1), do:
    • for initialize j := i + 1, when j < N, update (increase j by 1), do:
      • if square(a[i]) > square(a[j]), then:
        • swap a[i] and a[j]

Example

Let us see the following implementation to get better understanding −

#include <stdio.h>
#define N 3
struct Triangle{
   int a, b, c;
};
int square(struct Triangle t){
    int a = t.a, b = t.b, c = t.c;
    return (a + b + c)*(a + b - c)*(a - b + c)*(-a + b + c);
}
void solve(struct Triangle* a){
    for (int i = 0; i < N; i++)
        for (int j = i + 1; j < N; j++)
            if (square(a[i]) > square(a[j])){
                struct Triangle temp = a[i];
                a[i] = a[j];
                a[j] = temp;
            }
}
int main(){
    struct Triangle triangles[N] = {{7, 24, 25}, {5, 12, 13}, {3, 4, 5}};
    solve(triangles);
    for (int i = 0; i < N; i++){
        printf("(%d, %d, %d)\n", triangles[i].a, triangles[i].b, triangles[i].c);
    }
}

Input

{{7, 24, 25}, {5, 12, 13}, {3, 4, 5}}

Output

(3, 4, 5)
(5, 12, 13)
(7, 24, 25)
raja
Published on 08-Oct-2021 11:26:27
Advertisements