Java Program to Replace Each Element of Array By its Corresponding Rank

In this article we are going to see how we can replace each element of an array by its corresponding rank.

Java Program to Replace Each Element of Array By its Corresponding Rank

Approach:

  • Create an array with some elements.
  • Print the original array.
  • Pass the array into the ranking function.
  • The function creates a map and then stores all the elements with their index, and as maps are sorted it sorts the elements.
  • According to the map elements store the ranking into the array at their original index
  • Print the ranking index

Program:

import java.util.*;
public class Main
{
    public static void main(String[] args)
    {
        int arr[] = { 50, 20,95, 15, 99, 45 };
        System.out.println("The original array is- "+Arrays.toString(arr));
        ranking(arr);
        // print the ranking array
        System.out.println("The ranking array is- "+Arrays.toString(arr));
    }
    public static void ranking(int arr[])
    {
        // create a map
        Map<Integer, Integer> arrayMap = new TreeMap<>();
        // store the elements with its index in the map
        for (int i = 0; i < arr.length; i++) 
        {
            arrayMap.put(arr[i], i);
        }
        // Starting rank from 1
        int rank = 1;
        // Replace the elements with their ranks
        for (var val: arrayMap.values())
        {
            arr[val] = rank++;
        }
    }
}
Output:

The original array is- [50, 20, 95, 15, 99, 45]
The ranking array is- [4, 2, 5, 1, 6, 3]

Guys who are serious about learning the concepts of the java programming language should practice this list of programs in java and get a good grip on it for better results in exams or interviews.

Leave a Comment