Please login

Prime

Prepinsta Prime

Video courses for company/skill based Preparation

(Check all courses)
Get Prime Video
Prime

Prepinsta Prime

Purchase mock tests for company/skill building

(Check all mocks)
Get Prime mock

Reorder array using given indexes

reorder using array

Reorder array using given indexes in Java.

Problem statement:

Given two integer arrays of the same size, “a[ ] ” and “index[ ]”, reorder elements in “a[ ]” according to the given index array. 

Example:

Input:

a[ ] = [50, 40, 70, 60, 90]

index[ ] = [3, 0, 4, 1, 2] Output:

a[ ] = [40, 60, 90, 50, 70]

index[ ] = [0, 1, 2, 3, 4]

Algorithm:

  •  Start
  • use a temporary array temp[] of the same size as given arrays.
  • Traverse the given array and put all elements at their correct place in temp[] using index[].
  • Finally copy temp[] to a[] and set all values of index[i] as i. 
  • End
     

Java code :


import java.util.Arrays;

class prepinsta
{
    static int a[] = new int[]{5040706090};
    static int index[] = new int[]{30412};
    
    // Method to reorder elements of a[] according
    // to index[]
    static void reorder()
    {
        int temp[] = new int[a.length];
    
        // a[i] should be present at index[i] index
        for (int i=0; i<a.length; i++)
            temp[index[i]] = a[i];
    
        // Copy temp[] to a[]
        for (int i=0; i<a.length; i++)
        { 
        a[i] = temp[i];
        index[i] = i;
        }
    }
    
    // Driver method to prepinsta the above function
    public static void main(String[] args
    {
        
        reorder();
        
        System.out.println(“Reordered array is: “);
        System.out.println(Arrays.toString(a));
        System.out.println(“Modified Index array is:”);
        System.out.println(Arrays.toString(index));
        
    }
}
Output:
Reordered array is: 40 60 90 50 70 Modified Index array is: 0 1 2 3 4