Java Program to Reorder an Array According to Given indexes

In the previous article, we have seen Java Program to Double All the Negative Integers of the Array

In this article we are going to see how to reorder an array according to given indices using java programming language.

Java Program to Reorder an Array According to Given indexes

Array is a data structure which stores a fixed size sequential collection of values of single type. Where with every array elements/values memory location is associated. Each array elements have it’s own index where array index starts from 0.

In Array set of variables referenced by a single variable name and it’s array index position. It is also called as a container object which contains elements of similar type.

Declaration of an array:

dataType[] arrayName; (or)                              //Declaring an array
dataType []arrayName; (or)
dataType arr[];

Instantiation of an Array:

arrayName = new datatype[size];                    //Allocating memory to array

Combining both Statements in One:

dataType[] arrayName = new dataType[size] //Declaring and Instantiating array

Initialization of an Array:

arrayName[index-0]= arrayElement1             //Initializing the array

...

arrayName[index-s]= arrayElementS

Combining all Statements in One:

dataType arrayName[ ]={e1,e2,e3};               //declaration, instantiation and initialization

Method: Java Program to Reorder an Array According to Given indexes By Using a Third Array

Approach:

  • Initialize a third array say thirdArray of same size as given arrays.
  • Traverse the given array and put all elements at their correct place in thirdArray[] using index[].
  • Copy thirdArray[] to arr[] and set all values of index[i] as i.

Program:

import java.util.Arrays;

public class Main 
{
    public static void main(String[] args) 
    {
        int[] nums = { 1, 2, 3, 4 };
        int[] idx = { 3, 2, 1, 0 };
        reorder(nums, idx);
    }

    public static void reorder(int[] nums, int[] idx) 
    {
        // initialize a new array
        int[] thirdArray = new int[nums.length];
        System.out.println("Original array: "  + Arrays.toString(nums));

        // loop through the array
        for (int i = 0; i < nums.length; i++) 
        {
            // get the index of the element
            thirdArray[i] = nums[idx[i]];
        }
        for (int i = 0; i < nums.length; i++) 
        {
            // replace the element with the element at the index
            nums[i] = thirdArray[i];

        }
        System.out.println("Modified array:" + Arrays.toString(nums));
    }

}

Output:

Original array: [1, 2, 3, 4]
Modified array:[4, 3, 2, 1]

Are you new to the java programming language? We recommend you to ace up your practice session with these Basic Java Programs Examples

Related Java Programs: