Java Online Compiler
Example: Replace Array Elements by Rank using Brute Force in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// Replace Array Elements by Rank using Brute Force import java.util.Arrays; // Main class containing the entry point of the program public class Main { public static void main(String[] args) { // Step 1: Define the input array int[] originalArray = {10, 40, 20, 40, 30}; System.out.println("Original Array: " + Arrays.toString(originalArray)); // Step 2: Create a new array to store the ranked elements int[] rankedArray = new int[originalArray.length]; // Step 3: Iterate through each element of the original array for (int i = 0; i < originalArray.length; i++) { int currentElement = originalArray[i]; int rank = 1; // Ranks are 1-based // Step 4: For each element, count how many elements are smaller than it for (int j = 0; j < originalArray.length; j++) { // If another element is strictly smaller than the current element, // it contributes to increasing the current element's rank. if (originalArray[j] < currentElement) { rank++; } } // Step 5: Assign the calculated rank to the current element's position rankedArray[i] = rank; } // Step 6: Print the ranked array System.out.println("Ranked Array (Approach 2): " + Arrays.toString(rankedArray)); } }
Output
Clear
ADVERTISEMENTS