Open In App

Reorder an array according to given indexes

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

Example: 



Input:  arr[]   = [10, 11, 12];
            index[] = [1, 0, 2];
Output: arr[]   = [11, 10, 12]
           index[] = [0,  1,  2] 

Input:  arr[]   = [50, 40, 70, 60, 90]
          index[] = [3,  0,  4,  1,  2]
Output: arr[]   = [40, 60, 90, 50, 70]
          index[] = [0,  1,  2,  3,   4]



Reorder an array according to given indexes using Sorting:

The idea is to use an array of pairs to associate elements from the arr[] array with their respective indices from the index[] array and then sort these pairs based on the indices.

Follow the steps to solve the problem:

Below is the implementation of above approach:




#include <bits/stdc++.h>
 
using namespace std;
 
// Comparator function to sort pairs based on the second
// element
bool comp(const pair<int, int>& v1,
          const pair<int, int>& v2)
{
    // Sort in ascending order of index values
    return v1.second < v2.second;
}
 
// Function to reorder elements of arr[] according to
// index[]
void reorder(int arr[], int index[], int n)
{
    // Create a vector of pairs, where each pair stores the
    // original element (arr[i]) and its corresponding index
    // (index[i])
    vector<pair<int, int> > a(n);
 
    for (int i = 0; i < n; i++) {
        a[i].first = arr[i];
        a[i].second = index[i];
    }
 
    // Sort the vector of pairs based on the second element
    // (index) using the comp() comparator function
    sort(a.begin(), a.end(), comp);
 
    // Copy the sorted elements back to the original arr[]
    for (int i = 0; i < n; i++) {
        arr[i] = a[i].first;
    }
}
 
// Driver program
int main()
{
    int arr[] = { 50, 40, 70, 60, 90 };
    int index[] = { 3, 0, 4, 1, 2 };
    int n = sizeof(arr) / sizeof(arr[0]);
 
    // Call the reorder function to rearrange elements in
    // arr[] based on index[]
    reorder(arr, index, n);
 
    cout << "Reordered array is: \n";
    for (int i = 0; i < n; i++)
        cout << arr[i] << " ";
 
    return 0;
}




import java.util.Arrays;
import java.util.Comparator;
 
public class ReorderArray {
 
    // Comparator function to sort pairs based on the second
    // element
    static class PairComparator
        implements Comparator<int[]> {
        @Override
        public int compare(int[] pair1, int[] pair2)
        {
            // Sort in ascending order of index values
            return Integer.compare(pair1[1], pair2[1]);
        }
    }
 
    // Function to reorder elements of arr[] according to
    // index[]
    static void reorder(int[] arr, int[] index, int n)
    {
        // Create a 2D array to store pairs (original
        // element, index)
        int[][] pairs = new int[n][2];
 
        // Populate the pairs array
        for (int i = 0; i < n; i++) {
            pairs[i][0] = arr[i];
            pairs[i][1] = index[i];
        }
 
        // Sort the pairs array based on the second element
        // (index)
        Arrays.sort(pairs, new PairComparator());
 
        // Copy the sorted elements back to the original
        // arr[]
        for (int i = 0; i < n; i++) {
            arr[i] = pairs[i][0];
        }
    }
 
    // Driver program
    public static void main(String[] args)
    {
        int[] arr = { 50, 40, 70, 60, 90 };
        int[] index = { 3, 0, 4, 1, 2 };
        int n = arr.length;
 
        // Call the reorder function to rearrange elements
        // in arr[] based on index[]
        reorder(arr, index, n);
 
        System.out.println("Reordered array is: ");
        for (int i : arr) {
            System.out.print(i + " ");
        }
    }
}




def reorder(arr, index):
    n = len(arr)
    result = [0] * n
 
    for i in range(n):
        result[index[i]] = arr[i]
 
    # Copy the reordered elements back to the original arr[]
    for i in range(n):
        arr[i] = result[i]
 
 
if __name__ == "__main__":
    arr = [50, 40, 70, 60, 90]
    index = [3, 0, 4, 1, 2]
 
    # Call the reorder function to rearrange elements in arr[] based on index[]
    reorder(arr, index)
 
    print("Reordered array is:")
    print(" ".join(map(str, arr)))




using System;
 
class Program {
    // Function to reorder elements of arr[] according to
    // index[]
    static void Reorder(int[] arr, int[] index)
    {
        int n = arr.Length;
        int[] result = new int[n];
 
        for (int i = 0; i < n; i++) {
            result[index[i]] = arr[i];
        }
 
        // Copy the reordered elements back to the original
        // arr[]
        Array.Copy(result, arr, n);
    }
 
    static void Main()
    {
        int[] arr = { 50, 40, 70, 60, 90 };
        int[] index = { 3, 0, 4, 1, 2 };
        int n = arr.Length;
 
        // Call the Reorder function to rearrange elements
        // in arr[] based on index[]
        Reorder(arr, index);
 
        Console.WriteLine("Reordered array is:");
        Console.WriteLine(string.Join(" ", arr));
    }
}




// Comparator function to sort pairs based on the second element
function comp(v1, v2) {
    // Sort in ascending order of index values
    return v1[1] - v2[1];
}
 
// Function to reorder elements of arr[] according to index[]
function reorder(arr, index) {
    // Create an array of pairs, where each pair stores the
    // original element (arr[i]) and its corresponding index (index[i])
    const a = arr.map((value, i) => [value, index[i]]);
 
    // Sort the array of pairs based on the second element (index)
    a.sort(comp);
 
    // Copy the sorted elements back to the original arr[]
    for (let i = 0; i < arr.length; i++) {
        arr[i] = a[i][0];
    }
}
 
// Driver program
const arr = [50, 40, 70, 60, 90];
const index = [3, 0, 4, 1, 2];
 
// Call the reorder function to rearrange elements in arr[] based on index[]
reorder(arr, index);
 
console.log("Reordered array is:");
console.log(arr.join(" "));

Output
Reordered array is: 
40 60 90 50 70 






Time Complexity: O(n log n)
Auxiliary Space: O(n)

Reorder an array according to given indexes using Auxiliary Array:

The idea is to use an auxiliary array temp[] of same size as given arrays. Traverse the given array and put all elements at their correct place in temp[] using index[].

Follow the steps to solve the problem:

Below is the implementation of above approach:




// C++ program to sort an array according to given
// indexes
#include<iostream>
 
using namespace std;
 
// Function to reorder elements of arr[] according
// to index[]
void reorder(int arr[], int index[], int n)
{
    int temp[n];
 
    // arr[i] should be present at index[i] index
    for (int i=0; i<n; i++)
        temp[index[i]] = arr[i];
 
    // Copy temp[] to arr[]
    for (int i=0; i<n; i++)
    {
       arr[i]   = temp[i];
       index[i] = i;
    }
}
 
// Driver program
int main()
{
    int arr[] = {50, 40, 70, 60, 90};
    int index[] = {3,  0,  4,  1,  2};
    int n = sizeof(arr)/sizeof(arr[0]);
 
    reorder(arr, index, n);
 
    cout << "Reordered array is: \n";
    for (int i=0; i<n; i++)
        cout << arr[i] << " ";
 
}




//Java to find positions of zeroes flipping which
// produces maximum number of consecutive 1's
 
import java.util.Arrays;
 
class Test
{
    static int arr[] = new int[]{50, 40, 70, 60, 90};
    static int index[] = new int[]{30412};
     
    // Method to reorder elements of arr[] according
    // to index[]
    static void reorder()
    {
        int temp[] = new int[arr.length];
      
        // arr[i] should be present at index[i] index
        for (int i=0; i<arr.length; i++)
            temp[index[i]] = arr[i];
      
        // Copy temp[] to arr[]
        for (int i=0; i<arr.length; i++)
        {
           arr[i]   = temp[i];
           index[i] = i;
        }
    }
     
    // Driver method to test the above function
    public static void main(String[] args)
    {
         
        reorder();
         
        System.out.println("Reordered array is: ");
        System.out.println(Arrays.toString(arr));
        System.out.println("Modified Index array is:");
        System.out.println(Arrays.toString(index));
         
    }
}




# Python3 program to sort
# an array according to given
# indexes
 
# Function to reorder
# elements of arr[] according
# to index[]
def reorder(arr,index, n):
 
    temp = [0] * n;
 
    # arr[i] should be
        # present at index[i] index
    for i in range(0,n):
        temp[index[i]] = arr[i]
 
    # Copy temp[] to arr[]
    for i in range(0,n):
        arr[i] = temp[i]
        index[i] = i
     
# Driver program
arr = [50, 40, 70, 60, 90]
index = [3, 0, 4, 1, 2]
n = len(arr)
 
reorder(arr, index, n)
 
print("Reordered array is:")
for i in range(0,n):
    print(arr[i],end = " ")
 
print("\nModified Index array is:")
for i in range(0,n):
    print(index[i],end = " ")
 
# This code is contributed by
# Smitha Dinesh Semwal




// C# to find positions of zeroes flipping which
// produces maximum number of consecutive 1's
using System;
  
public class Test{
     
    static int []arr = new int[]{50, 40, 70, 60, 90};
    static int []index = new int[]{3,  0,  4,  1,  2};
      
    // Method to reorder elements of arr[] according
    // to index[]
    static void reorder()
    {
        int []temp = new int[arr.Length];
       
        // arr[i] should be present at index[i] index
        for (int i=0; i<arr.Length; i++)
            temp[index[i]] = arr[i];
       
        // Copy temp[] to arr[]
        for (int i=0; i<arr.Length; i++)
        {
           arr[i]   = temp[i];
           index[i] = i;
        }
    }
      
    // Driver method to test the above function
    public static void Main()
    {
          
        reorder();
          
        Console.WriteLine("Reordered array is: ");
        Console.WriteLine(string.Join(",", arr));
        Console.WriteLine("Modified Index array is:");
        Console.WriteLine(string.Join(",", index));
          
    }
}
/*This code is contributed by 29AjayKumar*/




<script>
      // JavaScript program to sort an array according to given
      // indexes
 
      // Function to reorder elements of arr[] according
      // to index[]
      function reorder(arr, index, n) {
        var temp = [...Array(n)];
 
        // arr[i] should be present at index[i] index
        for (var i = 0; i < n; i++) temp[index[i]] = arr[i];
 
        // Copy temp[] to arr[]
        for (var i = 0; i < n; i++) {
          arr[i] = temp[i];
          index[i] = i;
        }
      }
 
      // Driver program
 
      var arr = [50, 40, 70, 60, 90];
      var index = [3, 0, 4, 1, 2];
      var n = arr.length;
 
      reorder(arr, index, n);
 
      document.write("Reordered array is: ");
      document.write("<br>");
      for (var i = 0; i < n; i++) document.write(arr[i] + " ");
      document.write("<br>");
      document.write("Modified Index array is: ");
      document.write("<br>");
      for (var i = 0; i < n; i++) document.write(index[i] + " ");
       
      // This code is contributed by rdtank.
    </script>




<?php
// PHP program to sort an array
// according to given indexes
 
// Function to reorder elements
// of arr[] according to index[]
function reorder($arr, $index, $n)
{
    // $temp[$n];
 
    // arr[i] should be present
    // at index[i] index
    for ($i = 0; $i < $n; $i++)
    {
        $temp[$index[$i]] = $arr[$i];
    }
     
     
    // Copy temp[] to arr[]
    for ($i = 0; $i < $n; $i++)
    {
        $arr[$i] = $temp[$i];
        $index[$i] = $i;
    }
     
    echo "Reordered array is: \n";
for ($i = 0; $i < $n; $i++)
{
    echo $arr[$i] . " ";
}
 
echo "\nModified Index array is: \n";
for ($i = 0; $i < $n; $i++)
{
    echo $index[$i] . " ";
}
}
 
// Driver Code
$arr = array(50, 40, 70, 60, 90);
$index = array(3, 0, 4, 1, 2);
$n = sizeof($arr);
 
reorder($arr, $index, $n);
 
// This code is contributed
// by Abby_akku
?>

Output
Reordered array is: 
40 60 90 50 70 






Time Complexity: O(n) 
Auxiliary Space: O(n)

Reorder an array according to given indexes using Cyclic Sort:

The idea is use cyclic sort technique to reorder elements in the arr[] array based on the specified index[]. It iterates through the elements of arr[] and, for each element, continuously swaps it with the element at its correct position according to index[]. The process continues until each element is at its intended position, ensuring the desired order is achieved.

Follow the steps to solve the problem:

Below is the implementation of the above algorithm. 




// sort an array according to given indexes
#include<iostream>
 
using namespace std;
 
// Function to reorder elements of arr[] according
// to index[]
void reorder(int arr[], int index[], int n)
{
    // Fix all elements one by one
    for (int i=0; i<n; i++)
    {
        // While index[i] and arr[i] are not fixed
        while (index[i] != i)
        {
            // Store values of the target (or correct)
            // position before placing arr[i] there
            int  oldTargetI  = index[index[i]];
            char oldTargetE  = arr[index[i]];
 
            // Place arr[i] at its target (or correct)
            // position. Also copy corrected index for
            // new position
            arr[index[i]] = arr[i];
            index[index[i]] = index[i];
 
            // Copy old target values to arr[i] and
            // index[i]
            index[i] = oldTargetI;
            arr[i]   = oldTargetE;
        }
    }
}
 
// Driver program
int main()
{
    int arr[] = {50, 40, 70, 60, 90};
    int index[] = {3,  0,  4,  1,  2};
    int n = sizeof(arr)/sizeof(arr[0]);
 
    reorder(arr, index, n);
 
    cout << "Reordered array is: \n";
    for (int i=0; i<n; i++)
        cout << arr[i] << " ";
 
    
    return 0;
}




//A O(n) time and O(1) extra space Java program to
//sort an array according to given indexes
 
import java.util.Arrays;
 
class Test
{
    static int arr[] = new int[]{50, 40, 70, 60, 90};
    static int index[] = new int[]{30412};
     
    // Method to reorder elements of arr[] according
    // to index[]
    static void reorder()
    {
        // Fix all elements one by one
        for (int i=0; i<arr.length; i++)
        {
            // While index[i] and arr[i] are not fixed
            while (index[i] != i)
            {
                // Store values of the target (or correct)
                // position before placing arr[i] there
                int  oldTargetI  = index[index[i]];
                char oldTargetE  = (char)arr[index[i]];
      
                // Place arr[i] at its target (or correct)
                // position. Also copy corrected index for
                // new position
                arr[index[i]] = arr[i];
                index[index[i]] = index[i];
      
                // Copy old target values to arr[i] and
                // index[i]
                index[i] = oldTargetI;
                arr[i]   = oldTargetE;
            }
        }
    }
     
    // Driver method to test the above function
    public static void main(String[] args)
    {
         
        reorder();
         
        System.out.println("Reordered array is: ");
        System.out.println(Arrays.toString(arr));
        System.out.println("Modified Index array is:");
        System.out.println(Arrays.toString(index));
         
    }
}




# A O(n) time and O(1) extra space Python3 program to
# sort an array according to given indexes
 
# Function to reorder elements of arr[] according
# to index[]
def reorder(arr, index, n):
 
    # Fix all elements one by one
    for i in range(0,n):
 
           #  While index[i] and arr[i] are not fixed
           while (index[i] != i):
         
               # Store values of the target (or correct)
               # position before placing arr[i] there
               oldTargetI = index[index[i]]
               oldTargetE = arr[index[i]]
 
               # Place arr[i] at its target (or correct)
               # position. Also copy corrected index for
               # new position
               arr[index[i]] = arr[i]
               index[index[i]] = index[i]
 
               # Copy old target values to arr[i] and
               # index[i]
               index[i] = oldTargetI
               arr[i] = oldTargetE
 
 
# Driver program
arr = [50, 40, 70, 60, 90]
index= [3, 0, 4, 1, 2]
n = len(arr)
 
reorder(arr, index, n)
 
print("Reordered array is:")
for  i in range(0, n):
    print(arr[i],end=" ")
 
print("\nModified Index array is:")
for i in range(0, n):
    print(index[i] ,end=" ")
 
# This code is contributed by
# Smitha Dinesh Semwal




//A O(n) time and O(1) extra space C# program to
//sort an array according to given indexes
using System;
 
public class Test
{
    static int []arr = new int[]{50, 40, 70, 60, 90};
    static int []index = new int[]{3,  0,  4,  1,  2};
      
    // Method to reorder elements of arr[] according
    // to index[]
    static void reorder()
    {
        // Fix all elements one by one
        for (int i=0; i<arr.Length; i++)
        {
            // While index[i] and arr[i] are not fixed
            while (index[i] != i)
            {
                // Store values of the target (or correct)
                // position before placing arr[i] there
                int  oldTargetI  = index[index[i]];
                char oldTargetE  = (char)arr[index[i]];
       
                // Place arr[i] at its target (or correct)
                // position. Also copy corrected index for
                // new position
                arr[index[i]] = arr[i];
                index[index[i]] = index[i];
       
                // Copy old target values to arr[i] and
                // index[i]
                index[i] = oldTargetI;
                arr[i]   = oldTargetE;
            }
        }
    }
      
    // Driver method to test the above function
    public static void Main()
    {
          
        reorder();
          
        Console.WriteLine("Reordered array is: ");
        Console.WriteLine(String.Join(" ",arr));
        Console.WriteLine("Modified Index array is:");
        Console.WriteLine(String.Join(" ",index));
          
    }
}
 
// This code is contributed by PrinciRaj1992




<script>
// A O(n) time and O(1) extra space JavaScript program to
// sort an array according to given indexes
 
// Function to reorder elements of arr[] according
// to index[]
function reorder(arr, index, n)
{
    // Fix all elements one by one
    for (let i=0; i<n; i++)
    {
        // While index[i] and arr[i] are not fixed
        while (index[i] != i)
        {
            // Store values of the target (or correct)
            // position before placing arr[i] there
            let oldTargetI = index[index[i]];
            let oldTargetE = arr[index[i]];
 
            // Place arr[i] at its target (or correct)
            // position. Also copy corrected index for
            // new position
            arr[index[i]] = arr[i];
            index[index[i]] = index[i];
 
            // Copy old target values to arr[i] and
            // index[i]
            index[i] = oldTargetI;
            arr[i] = oldTargetE;
        }
    }
}
 
// Driver program
    let arr = [50, 40, 70, 60, 90];
    let index = [3, 0, 4, 1, 2];
    let n = arr.length;
 
    reorder(arr, index, n);
 
    document.write("Reordered array is: <br>");
    for (let i=0; i<n; i++)
        document.write(arr[i] + " ");
 
    document.write("<br>Modified Index array is: <br>");
    for (let i=0; i<n; i++)
        document.write(index[i] + " ");
 
 
 
 
// This code is contributed by Surbhi Tyagi.
</script>

Output
Reordered array is: 
40 60 90 50 70 






Time Complexity: O(n) 
Auxiliary Space: O(1)

Reorder an array according to given indexes using Mathematics Approach:

Follow the steps to solve the problem by the above approach:

Below is the implementation of the above algorithm. 




// C++ code for the above approach
#include <climits>
#include <iostream>
using namespace std;
 
 
int findMax(int arr[], int n)
{
    int Max = INT_MIN;
    for (int i = 0; i < n; i++) {
        if (Max < arr[i])
            Max = arr[i];
    }
    return Max;
}
 
// result = (original + update%z*z)  ..
void rearrange(int arr[], int index[], int n)
{
    int z = findMax(arr, n) + 1;
    for (int i = 0; i < n; i++) {
        arr[index[i]] = arr[index[i]] % z + arr[i] % z * z;
    }
    for (int i = 0; i < n; i++) {
        arr[i] = arr[i] / z;
    }
}
 
int main()
{
    int arr[] = { 23, 12, 20, 10, 23 };
    int index[] = { 4, 0, 1, 2, 3 };
 
    rearrange(arr, index, 5);
    cout << "Reordered array is: \n";
    for (int i = 0; i < 5; i++)
        cout << arr[i] << " ";
 
    return 0;
}
 
// This code is contributed by lokesh




/*package whatever //do not write package name here */
 
import java.io.*;
 
class GFG {
    public static void main(String[] args)
    {
        int arr[] = { 23, 12, 20, 10, 23 };
        int index[] = { 4, 0, 1, 2, 3 };
 
        rearrange(arr, index);
        printArray(arr);
    }
    private static void printArray(int arr[])
    {
        for (int i = 0; i < arr.length; i++)
            System.out.print(arr[i] + " ");
    }
    //    result = (original + update%z*z)  ..
    private static void rearrange(int[] arr, int[] index)
    {
        int z = findMax(arr) + 1;
        for (int i = 0; i < arr.length; i++) {
            arr[index[i]]
                = arr[index[i]] % z + arr[i] % z * z;
        }
        for (int i = 0; i < arr.length; i++) {
            arr[i] = arr[i] / z;
        }
    }
 
    private static int findMax(int[] arr)
    {
        int max = Integer.MIN_VALUE;
        for (int i = 0; i < arr.length; i++) {
            if (max < arr[i])
                max = arr[i];
        }
        return max;
    }
}




# Python implementation for the above approach
def printArray(arr):
    for i in range(len(arr)):
        print(arr[i], end=" ")
 
# result = (original + update%z*z) ..
def rearrange(arr, index):
    z = findMax(arr) + 1
    for i in range(len(arr)):
        arr[index[i]] = arr[index[i]] % z + arr[i] % z * z
 
    for i in range(len(arr)):
        arr[i] = arr[i]//z
 
 
def findMax(arr):
    Max = float("-inf")
    for i in range(len(arr)):
        if(Max < arr[i]):
            Max = arr[i]
 
    return Max
 
arr = [23, 12, 20, 10, 23]
index = [4, 0, 1, 2, 3]
 
rearrange(arr, index)
printArray(arr)
 
# This code is contributed by lokesh




// C# implementation for the above approach
using System;
 
public class GFG {
 
    static public void Main()
    {
 
        // Code
        int[] arr = { 23, 12, 20, 10, 23 };
        int[] index = { 4, 0, 1, 2, 3 };
 
        rearrange(arr, index);
        printArray(arr);
    }
 
    private static void printArray(int[] arr)
    {
        for (int i = 0; i < arr.Length; i++)
            Console.Write(arr[i] + " ");
    }
    //    result = (original + update%z*z)  ..
    private static void rearrange(int[] arr, int[] index)
    {
        int z = findMax(arr) + 1;
        for (int i = 0; i < arr.Length; i++) {
            arr[index[i]]
                = arr[index[i]] % z + arr[i] % z * z;
        }
        for (int i = 0; i < arr.Length; i++) {
            arr[i] = arr[i] / z;
        }
    }
 
    private static int findMax(int[] arr)
    {
        int max = Int32.MinValue;
        for (int i = 0; i < arr.Length; i++) {
            if (max < arr[i])
                max = arr[i];
        }
        return max;
    }
}
 
// This code is contributed by lokeshmvs21.




// JavaScript implementation for the above approach
 
function printArray(){
    for(let i = 0; i < arr.length; i++){
        console.log(Math.trunc(arr[i]) + " ");
    }
}
 
//    result = (original + update%z*z)  ..
function rearrange(arr, index){
    var z = findMax(arr) + 1;
    for(let i = 0; i < arr.length; i++){
        arr[index[i]] = arr[index[i]] % z + arr[i] % z * z;
    }
    for(let i = 0; i < arr.length; i++){
        arr[i] = arr[i]/z;
    }
}
 
function findMax(arr){
    let max = Number.MIN_VALUE;
    for(let i = 0; i < arr.length; i++){
        if(max < arr[i]){
            max = arr[i];
        }
    }
    return max;
}
 
let arr = [ 23, 12, 20, 10, 23 ];
let index = [ 4, 0, 1, 2, 3 ];
 
rearrange(arr, index);
printArray(arr);
 
// This code is contributed by lokeshmvs21.

Output
12 20 10 23 23 






Time Complexity: O(N)
Auxiliary Space: O(1)


Article Tags :