- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 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]
- if square(a[i]) > square(a[j]), then:
- for initialize j := i + 1, when j < N, update (increase j by 1), do:
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)
", 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)
Advertisements