Sorting a list by multiple attributes involves ranking items
based on priority or weight assigned to each attribute. Two common techniques
for sorting are Lexicographic Sorting and Weighted Sorting.
Here's how each can be represented mathematically:
1. Lexicographic Sorting
This technique prioritizes attributes sequentially, similar
to sorting words in a dictionary.
Math Representation:
Assume each item in the list has mmm attributes: \(A_{1}, A_{2},
..., A_{m}\). The sorting function evaluates items \(X_{i}\) and \(X_{j}\)
as:
$$(X_{i} < X_{j}
if A_{1,i} < A_{1,j} or
(A_{1,i} = A_{1,j} and A_{2,i} < A_{2,j}))$$ and so on.
Steps:
- Compare
items by the first attribute \(A_{1}\).
- If
items tie on \(A_{1}\), compare on \(A_{2}\).
- Continue
comparing until a distinction is found.
Example:
Sort a list of people by age, then by height:
Ø Person
1: (Age = 25, Height = 5.9)
Ø Person
2: (Age = 20, Height = 6.0)
Ø Person
3: (Age = 25, Height = 5.8)
Sort order: Person 2 → Person 3 → Person 1.
2. Weighted Sorting
In weighted sorting, each attribute is assigned a weight
indicating its importance, and a score is computed for each item.
Sorting is done based on this score.
Math Representation:
Let \(w_{1}, w_{2}, ..., w_{m}\) be the weights of
attributes \(A_{1}, A_{2}, ..., A_{m}\) such that:
\(w_{1}+ w_{2}+ ...+ w_{m}=1\) (weights normalized to 1).
The score \(S_{i}\) for item i is:
\(S_{i}=w_{1}\cdot A_{1,i}+w_{2}\cdot A_{2,i}+ ..., w_{m}\cdot A_{m,i}\)
Sort items by descending \(S_{i}\)
Example:
Sort cars by fuel efficiency and cost:
Ø Car
1: (Fuel Efficiency = 30 MPG, Cost = $20,000)
Ø Car
2: (Fuel Efficiency = 25 MPG, Cost = $18,000)
Ø Car
3: (Fuel Efficiency = 35 MPG, Cost = $22,000)
Weights:
Ø Fuel
Efficiency: \(w_{1}=0.7\)
Ø Cost:
\(w_{2}=0.3\)
Scores:
Ø Car
1: S=0.7×30+0.3×20000=21+6000=6021
Ø Car
2: S=0.7×25+0.3×18000=17.5+5400=5417.5
Ø Car
3: S=0.7×35+0.3×22000=24.5+6600=6624.5
Sort order: Car 3 → Car 1 → Car 2.
Comparison
Ø Lexicographic
Sorting is useful when attributes have strict precedence.
Ø Weighted
Sorting is better for scenarios where attributes contribute proportionally
to the ranking.
Chained Comparator: Sorting Of a list multiple
attribute wise two technique First is multiple Class wise sorting Collections.sort(list, new StaffMemberChainedComparator( new StaffMemberNameComparer(),
new StaffMemberAgeComparator(),
new StaffMemberSalaryComparator()
) ); Single Class Comparator wise sorting Collections.sort(list, new Comparator<Object>() { public int compare(Object obj1, Object obj2)
{ StaffMember e1 = (StaffMember) obj1; StaffMember e2 = (StaffMember) obj2; int name =
e1.getName().compareTo(e2.getName()); Integer ooo1 = new
Integer(String.valueOf(e1.getAge())); Integer ooo2 = new
Integer(String.valueOf(e2.getAge())); int age = ooo1.compareTo(ooo2); int sal =
Double.compare(e1.getSalary(), e2.getSalary()); if
(name != 0) {
return name;
}else if(name ==0 && age!=0){
return age;
}else if(name ==0 && age==0 && sal!=0){
return sal; } return name; } }); |
Java
StaffMember
public class StaffMember
{ |
Java
StaffMemberAgeComparator
import java.util.Comparator; |
Java
StaffMemberChainedComparator
import java.util.Arrays; |
Java
StaffMemberNameComparer
import java.util.Comparator; |
Java
StaffMemberSalaryComparator
import java.util.Comparator; |
Java
StaffMemberSorting
import java.util.ArrayList; |
This Java implementation demonstrates sorting a list of StaffMember objects using a chained comparator approach. You are sorting the staffmembers by
multiple fields: name, age, and salary. Below is an explanation and breakdown
of how the different classes work together.
Step-by-Step Breakdown:
Step 1: StaffMember Class
This class holds the details of a staffMember: name, age, and
salary. It also overrides hashCode and equals methods for proper equality
checking.
Ø Fields:
name, age, salary
Ø Methods:
ü
getName(), getAge(), getSalary() – Getters for
the fields.
ü
setName(), setAge(), setSalary() – Setters for
the fields.
ü
hashCode() and equals() – For equality
comparison based on employee properties.
Step 2: EmployeeSorting Class
This is the main driver class that sorts the Employee list
using different comparator approaches.
- Adding
Employees to List: Several Employee objects are added to the list with
varying attributes like name, age, and salary.
- Chained
Comparator Sorting:
ü
You use Collections.sort() to sort the list
based on multiple comparators (name, age, and salary).
ü
The sorting is handled by the StaffMemberChainedComparator
class which accepts a list of comparators (StaffMemberNameCompare, StaffMemberAgeComparator, StaffmemberSalaryComparator).
- Single
Class Sorting:
ü
The sorting logic is implemented in a single
anonymous comparator class inside the Collections.sort() method. It compares StaffMember objects first by name, then age, and finally salary.
Step 3: StaffMemberChainedComparator Class
This class implements Comparator<StaffMember> and enables
chaining of multiple comparators.
Ø Constructor:
Accepts a var-args parameter of comparators.
Ø compare
Method: Loops through each comparator in the list and performs a comparison
between two StaffMember objects. If one comparison is non-zero (i.e., a difference
is found), it returns that result. Otherwise, it continues with the next
comparator.
Step 4: SatffMemberNameCompare Class
This class implements Comparator<StaffMember> and
compares two staff members by their name.
Ø compare
Method: Uses the String class’s compareTo method to compare the staff names lexicographically.
Step 5: StaffMemberAgeComparator Class
This class implements Comparator<StaffMember> and
compares two staff members by their age.
Ø compare
Method: Performs subtraction between emp1.getAge() and emp2.getAge(). If
the result is negative, emp1 is considered smaller; if positive, emp1 is
larger.
Step 6: StaffMemberSalaryComparator Class
This class implements Comparator<StaffMember> and
compares two staff members by their salary.
Ø compare
Method: Uses Double.compare() to compare the salary of two employees.
Example Output:
When sorting by multiple fields (name, age, and salary), the
output will look something like this:
Chained Comparator Output:
Plaintext output
Gopi---25---500.0 Hari---20---2000.0 Hari---25---500.0 Hari---25---1000.0 Kartik---24---5000.0 Kartik---25---1000.0 Kartik---25---5000.0 |
Single Class Design Output:
Plaintext output
Gopi---25---500.0 Hari---20---2000.0 Hari---25---500.0 Hari---25---1000.0 Kartik---24---5000.0 Kartik---25---1000.0 Kartik---25---5000.0 |
In both sorting implementations, the list of employees is
sorted first by name in ascending order, then by age in ascending order if the
names are the same, and finally by salary.
Summary:
Ø Chained
Comparator: Flexible, reusable, and maintainable. You can easily change or
add new fields to compare.
Ø Single
Class Comparator: Quick, but harder to maintain as you increase the number
of fields to compare.
By chaining comparators, the sorting logic becomes modular
and each comparator handles only one field. This is beneficial when dealing
with large objects and complex comparison logic.
For More DSA Related information, visit
Ø
Bench
mark of compiler using Ackerman function
Ø
To
check if the rows of a matrix are circularly identical in Java
Ø
Frequency
Weaving Logic & Spiral Printing of a Rectangle
Ø
Zig Zag
Matrix print multiple way
Ø
Gready
Algorithm’s or knapsack algorithms
Ø
understanding
recursive method for binary tree
Ø
Dynamic
Programming: Max Square Sub-matrix of 1s in a Matrix
Ø
Previous and
Next Date Palindrome
Ø
Karatsuba's
Algorithm for multiplying two large numbers
Ø
Multiplication
In different Way
Ø
Time
Analysis for Congested Routes Using Shortest Path Algorithms
For More Java Related information, visit
Ø
Streams
Lambdas Collectors and Functional Interfaces in Java 8
Ø
Java
8 support static method or default method or both in the interface
Ø
Serialization
understanding
Ø
Garbage
Collection Under Standing
Ø
How
work Garbage Collection in Java
Ø
Under
Standing Of Mutable and Immutable Class
For Other information, visit
Ø
How
to get the neighbor of binary tree
Ø OWASP
(Open Web Application Security Project)
Ø Mastering
Debounce, Throttle, Rate Limit & Backoff in Java
Ø How
to draw sequence diagram and other diagrams using plantuml
Ø
Molecular
weight of chemistry in Java code
Ø
String
to xml or html Beautifier
Ø
Key
Components of Apache Kafka for Scalable Messaging
Ø
Build
a Video Stream Microservice with Kafka & REST API in Java
Ø
Kafka
general questions and answers
0 Comments