VOOZH about

URL: https://www.geeksforgeeks.org/java/sort-students-by-marks-in-java/

⇱ Sort students by marks in Java - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Sort students by marks in Java

Last Updated : 30 Jan, 2026

The arrays roll[] and marks[] store student roll numbers and their corresponding marks. The objective is to reorder the roll numbers such that they follow the descending order of marks, while maintaining the correct roll-marks association.

Example:

Input: roll[] = {101, 108, 103, 105}, marks[] = {70, 80, 40, 90}
Output: {105, 108, 101, 103}
Explanation: After sorting marks[] in decreasing order as {90, 80, 70, 40}, the corresponding roll[] values are rearranged to {105, 108, 101, 103} respectively.

Approach

Follow these steps to solve the problem efficiently:

  • Create a custom Student class to store marks and the corresponding roll number together
  • Traverse both arrays and store each marks–roll pair as a Student object in an ArrayList
  • Sort the list using Collections.sort() based on marks in decreasing order
  • Traverse the sorted list and print the roll numbers in the new order based on marks

Output
105 108 101 103 
  • Time Complexity: O(N log N), where N is the number of students.
  • Space Complexity: O(N) due to the ArrayList storing the student objects.
Comment
Article Tags:
Article Tags: