Sort an Array of Objects According to a Custom Criteria

Last Updated : 30 Jun, 2026

Most programming languages provide built-in sorting functions that allow objects to be sorted using a user-defined comparison rule or key function. This makes it easy to sort records based on one or more data members without modifying the sorting algorithm.

Let us consider the following example to understand.

Given an array of Student objects, where each object contains the student's name (in lowercase letters) and marks obtained in an exam, sort the array in descending order of marks. If two or more students have the same marks, sort them in lexicographical order of their names.

Examples:

Input:
michal 56
john 100
abbas 98
jordan 45
Output: 
john 100
abbas 98
michal 56
jordan 45
Explanation: The marks of students in decreasing order are 100, 98, 56, 45. So, the sorted order is: john 100, abbas 98, michal 56, jordan 45.

Input:
rahul 90
aman 95
zara 90
bhavesh 95
Output:
aman 95
bhavesh 95
rahul 90
zara 90
Explanation: Among students scoring 95, aman comes before bhavesh. Among students scoring 90, rahul comes before zara. Hence the sorted order is: aman 95, bhavesh 95, rahul 90, zara 90.

The idea is to sort the array of Student objects using a custom comparison rule. The comparison first checks the marks in descending order. If two students have the same marks, their names are compared in lexicographical order to break the tie.

Sorting Support in Different Languages:

  • C: The library function qsort() accepts a user-defined comparator function.
  • C++: sort() function from the STL allows a comparator function, function object, or lambda expression.
  • Python: Python supports sorting objects through the key parameter of sort() and sorted().
  • JavaScript: sort() in JavaScript allows a custom comparison
  • Java: Java provides Collections.sort() and Arrays.sort() with Comparator. Structures (objects) can be sorted by implementing a custom comparator using a class, anonymous class, or lambda expression.
  • C#: C# provides List.Sort() and Array.Sort() with custom comparison support. Structures (objects) can be sorted using a comparison delegate or an IComparer<T> implementation.
C++
#include <bits/stdc++.h>
using namespace std;

class Student
{
  public:
    string name;
    int marks;

    Student(string n, int m)
    {
        name = n;
        marks = m;
    }
};

// Compares two students based on marks and name
static bool compare(const Student &s1, const Student &s2)
{

    // If marks are same, sort by name in lexicographical order
    if (s1.marks == s2.marks)
        return s1.name < s2.name;

    // Otherwise, sort by marks in descending order
    return s1.marks > s2.marks;
}

// Sorts the array of Student objects
vector<Student> sortMarks(vector<Student> &arr)
{
    sort(arr.begin(), arr.end(), compare);
    return arr;
}

int main()
{

    // Array of Student objects
    vector<Student> arr;

    arr.push_back(Student("rahul", 90));
    arr.push_back(Student("aman", 95));
    arr.push_back(Student("zara", 90));
    arr.push_back(Student("bhavesh", 95));

    // Sort the students
    vector<Student> ans = sortMarks(arr);

    // Print the sorted students
    for (Student &student : ans)
        cout << student.name << " " << student.marks << "\n";

    return 0;
}
Java
import java.util.*;

// Structure of Student class
class Student {
    String name;
    int marks;

    Student(String n, int m)
    {
        name = n;
        marks = m;
    }
}

public class GFG {

    // Sorts the array of Student objects
    static ArrayList<Student>
    sortMarks(ArrayList<Student> arr)
    {

        Collections.sort(arr, (s1, s2) -> {
            // If marks are same, sort by name in
            // lexicographical order
            if (s1.marks == s2.marks)
                return s1.name.compareTo(s2.name);

            // Otherwise, sort by marks in descending order
            return s2.marks - s1.marks;
        });

        return arr;
    }

    // Driver code
    public static void main(String[] args)
    {

        // Array of Student objects
        ArrayList<Student> arr = new ArrayList<>();

        arr.add(new Student("rahul", 90));
        arr.add(new Student("aman", 95));
        arr.add(new Student("zara", 90));
        arr.add(new Student("bhavesh", 95));

        // Sort the students
        ArrayList<Student> ans = sortMarks(arr);

        // Print the sorted students
        for (Student student : ans)
            System.out.println(student.name + " "
                               + student.marks);
    }
}
Python
from functools import cmp_to_key
from typing import List


class Student:
    def __init__(self, name: str, marks: int):
        self.name = name
        self.marks = marks

# Compares two students based on marks and name


def compare(s1: Student, s2: Student):
    # If marks are same, sort by name in lexicographical order
    if s1.marks == s2.marks:
        return s1.name < s2.name
    # Otherwise, sort by marks in descending order
    return s1.marks > s2.marks

# Sorts the array of Student objects


def sortMarks(arr: List[Student]):
    arr.sort(key=cmp_to_key(compare))
    return arr


if __name__ == '__main__':
    # Array of Student objects
    arr = [
        Student('rahul', 90),
        Student('aman', 95),
        Student('zara', 90),
        Student('bhavesh', 95)
    ]

    # Sort the students
    ans = sortMarks(arr)

    # Print the sorted students
    for student in ans:
        print(f'{student.name} {student.marks}')
C#
using System;
using System.Collections.Generic;

class Student {
    public string name;
    public int marks;

    public Student(string n, int m)
    {
        name = n;
        marks = m;
    }
}

class GFG {
    // Compares two students based on marks and name
    static int Compare(Student s1, Student s2)
    {
        if (s1.marks == s2.marks)
            return s1.name.CompareTo(s2.name);

        return s2.marks.CompareTo(s1.marks);
    }

    // Sorts the array of Student objects
    static List<Student> sortMarks(List<Student> arr)
    {
        arr.Sort(Compare);
        return arr;
    }

    static void Main()
    {
        List<Student> arr = new List<Student>();

        arr.Add(new Student("rahul", 90));
        arr.Add(new Student("aman", 95));
        arr.Add(new Student("zara", 90));
        arr.Add(new Student("bhavesh", 95));

        List<Student> ans = sortMarks(arr);

        foreach(Student student in ans) Console.WriteLine(
            student.name + " " + student.marks);
    }
}
JavaScript
class Student {
  constructor(name, marks) {
    this.name = name;
    this.marks = marks;
  }
}

// Compares two students based on marks and name
function compare(s1, s2) {
  // If marks are same, sort by name in lexicographical order
  if (s1.marks === s2.marks)
    return s1.name.localeCompare(s2.name);

  // Otherwise, sort by marks in descending order
  return s2.marks - s1.marks;
}

// Sorts the array of Student objects
function sortMarks(arr) {
  arr.sort(compare);
  return arr;
}

function main() {
  // Array of Student objects
  let arr = [
    new Student('rahul', 90),
    new Student('aman', 95),
    new Student('zara', 90),
    new Student('bhavesh', 95)
  ];

  // Sort the students
  let ans = sortMarks(arr);

  // Print the sorted students
  for (let student of ans)
    console.log(student.name + ' ' + student.marks);
}

main();

Output
aman 95
bhavesh 95
rahul 90
zara 90
Try It Yourself
redirect icon
Comment