Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
C program to sort triangles based on area
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 using sides is calculated with Heron's formula: 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)
Syntax
struct Triangle {
int a, b, c;
};
int square(struct Triangle t);
void sortTriangles(struct Triangle* triangles, int n);
Approach
To solve this, we will follow these steps ā
- Define triangle structure with sides a, b and c
- Create a function to calculate the squared area (avoiding floating point arithmetic)
- Use bubble sort to arrange triangles in ascending order of area
- Compare squared areas: (a + b + c) * (a + b - c) * (a - b + c) * (-a + b + c)
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 sortTriangles(struct Triangle* triangles) {
for (int i = 0; i < N; i++) {
for (int j = i + 1; j < N; j++) {
if (square(triangles[i]) > square(triangles[j])) {
struct Triangle temp = triangles[i];
triangles[i] = triangles[j];
triangles[j] = temp;
}
}
}
}
int main() {
struct Triangle triangles[N] = {{7, 24, 25}, {5, 12, 13}, {3, 4, 5}};
printf("Before sorting:<br>");
for (int i = 0; i < N; i++) {
printf("(%d, %d, %d)<br>", triangles[i].a, triangles[i].b, triangles[i].c);
}
sortTriangles(triangles);
printf("\nAfter sorting by area:<br>");
for (int i = 0; i < N; i++) {
printf("(%d, %d, %d)<br>", triangles[i].a, triangles[i].b, triangles[i].c);
}
return 0;
}
Before sorting: (7, 24, 25) (5, 12, 13) (3, 4, 5) After sorting by area: (3, 4, 5) (5, 12, 13) (7, 24, 25)
How It Works
- The
square()function calculates 16 times the squared area to avoid floating point operations - Triangle (3,4,5) has area 6, (5,12,13) has area 30, (7,24,25) has area 84
- Bubble sort compares adjacent triangles and swaps them if needed
- Time complexity is O(n²) due to nested loops
Conclusion
This program efficiently sorts triangles by area using integer arithmetic and Heron's formula. The bubble sort algorithm ensures triangles are arranged in ascending order of their calculated areas.
