VOOZH about

URL: https://www.geeksforgeeks.org/java/keeping-indexes-after-sorting-in-java/

⇱ Keeping indexes after sorting in Java - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Keeping indexes after sorting in Java

Last Updated : 28 Jan, 2026

Given an integer array, sort its elements in ascending order while retaining and displaying their original indexes, ensuring the initial positions of elements are preserved after sorting.

Examples:

Input: arr[] = {20, 40, 30, 10}

Output:
Element | Original index
10 | 3
20 | 0
30 | 2
40 | 1

Approach

Follow these steps to sort the array while keeping track of original indexes:

  • Define a class ArrItem to store each element and its original index.
  • Create an ArrayList of ArrItem objects from the array elements.
  • Sort the list using Collections.sort() with a custom comparator based on the element value.
  • Traverse the sorted list and print each element along with its original index.

Implementation


Output
4 3
5 2
10 1
20 0
Comment
Article Tags:
Article Tags: