Small Triangles, Large Triangles

You are given n triangles, specifically, their sides  and . Print them in the same style but sorted by their areas from the smallest one to the largest one. It is guaranteed that all the areas are different.

The best way to calculate the volume of the triangle with sides  and  is Heron's formula:

 where .


Example:

Input: n=3,triangle[]={{7,24,25},{5,12,13},{3,4,5}}
Output: 3 4 5
5 12 13
7 24 25

Approach

C

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

struct triangle
{
    int a;
    int b;
    int c;
};

typedef struct triangle triangle;

void sort_by_area(triangle *trint n)
{
    // Sort an array a of the length n
    int *p = malloc(n * sizeof(int));

    //find the area of each triangle
    for (int i = 0i < ni++)
    {
        float a = (tr[i].a + tr[i].b + tr[i].c) / 2.0;
        p[i] = (a * (a - tr[i].a) * (a - tr[i].b) * (a - tr[i].c));
    }

    //sort the array
    for (int i = 0i < ni++)
    {
        for (int j = 0j < n - i - 1j++)
        {
            if (p[j] > p[j + 1])
            {
                int temp = p[j];
                p[j] = p[j + 1];
                p[j + 1] = temp;

                temp = tr[j].a;
                tr[j].a = tr[j + 1].a;
                tr[j + 1].a = temp;
                temp = tr[j].b;
                tr[j].b = tr[j + 1].b;
                tr[j + 1].b = temp;
                temp = tr[j].c;
                tr[j].c = tr[j + 1].c;
                tr[j + 1].c = temp;
            }
        }
    }
}

int main()
{
    int n = 3;
    triangle *tr = malloc(n * sizeof(triangle));

    tr[0].a = 7tr[0].b = 24tr[0].c = 25;
    tr[1].a = 5tr[1].b = 12tr[1].c = 13;
    tr[2].a = 3tr[2].b = 4tr[2].c = 5;

    sort_by_area(trn);
    for (int i = 0i < ni++)
    {
        printf("%d %d %d\n"tr[i].atr[i].btr[i].c);
    }
    return 0;
}


No comments:

Post a Comment