Keeping indexes after sorting in Java

 The problem requires us to print the elements of an array in sorted order while also maintaining and printing their original indices. We can do this by declaring a class to represent each item of the array, which will contain two integers: the item value and its original index. We will then create an ArrayList of these class objects, sort them based on the item values, and finally print out the sorted elements along with their original indices.

To implement this solution, we start by declaring the ArrItem class which will contain the item value and its original index. We also declare a MyCmp class which will be used to compare two ArrItem objects and sort them based on their item values.

Next, we declare a function called printSortedWithIndexes which takes an integer array as input and prints out the sorted elements along with their original indices. Inside this function, we create an ArrayList of ArrItem objects and populate it with the items from the input array along with their original indices. We then use the Collections.sort method to sort the ArrayList based on the item values, using the MyCmp comparator. Finally, we loop over the sorted ArrayList and print out each element's item value and index.

Let's look at the Java implementation of this solution:

java
import java.util.*; class ArrItem { int item; int index; ArrItem(int im, int ix) { item = im; index = ix; } } class MyCmp implements Comparator<ArrItem> { public int compare(ArrItem i1, ArrItem i2) { return i1.item - i2.item; } } class GfG { static void printSortedWithIndexes(int arr[]) { int n = arr.length; ArrayList<ArrItem> al = new ArrayList<ArrItem>(n); for(int i=0; i<n; i++) { al.add(new ArrItem(arr[i], i)); } Collections.sort(al, new MyCmp()); for(ArrItem x: al) { System.out.println(x.item + " " + x.index); } } public static void main(String args[]) { int arr[] = {20, 40, 30, 10}; printSortedWithIndexes(arr); } }

If we run this code, we get the following output:

10 3 20 0 30 2 40 1

As we can see, the code correctly prints out the sorted elements along with their original indices, as required by the problem statement.

Previous Post Next Post