Reorder an array according to given indexes
Last Updated :
23 Jul, 2025
Given two integer arrays of the same length, arr[] and index[], the task is to reorder the elements in arr[] such that after reordering, each element from arr[i] moves to the position index[i]. The new arrangement reflects the values being placed at their target indices, as described by index[] array.
Example:
Input: arr[] = [10, 11, 12], index[] = [1, 0, 2]
Output: 11 10 12
Explanation: 10 moves to position 1, 11 to 0, and 12 stays at 2.
Input: arr[] = [1, 2, 3, 4], index[] = [3, 2, 0, 1]
Output: 3 4 2 1
Explanation: 1 moves to 3, 2 to 2, 3 to 0, 4 to 1.
Input: arr[] = [50, 40, 70, 60, 90], index[] = [3, 0, 4, 1, 2]
Output: 40 60 90 50 70
[Naive Approach] Using Sorting - O(n*log(n)) Time and O(n) Space
The idea is to pair each element in arr[] with its target position from index[] as a 2D array. These pairs are then sorted by index, which arranges elements in the order they should appear in the final array. After sorting, we extract only the values (second part of each pair) to build the reordered array.
C++
// C++ program to reorder arr[] using index[]
// using Naive approach
#include <bits/stdc++.h>
using namespace std;
// Function to reorder arr based on index
void reorderArray(vector<int> &arr,
vector<int> &index) {
// Pair each element with its target index
vector<vector<int>> paired;
for (int i = 0; i < arr.size(); i++) {
paired.push_back({index[i], arr[i]});
}
// Sort the pairs by index
sort(paired.begin(), paired.end());
// Rearrange arr based on sorted pairs
for (int i = 0; i < arr.size(); i++) {
arr[i] = paired[i][1];
}
}
// Driver code
int main() {
vector<int> arr = {10, 11, 12};
vector<int> index = {1, 0, 2};
reorderArray(arr, index);
// Print the updated array
for (int i = 0; i < arr.size(); i++) {
cout << arr[i] << " ";
}
return 0;
}
Java
// Java program to reorder arr[] using index[]
// using Naive approach
import java.util.*;
class GfG {
// Function to reorder arr based on index
static void reorderArray(int[] arr, int[] index) {
// Pair each element with its target index
List<int[]> paired = new ArrayList<>();
for (int i = 0; i < arr.length; i++) {
paired.add(new int[]{index[i], arr[i]});
}
// Sort the pairs by index
Collections.sort(paired, (a, b) -> Integer.compare(a[0], b[0]));
// Rearrange arr based on sorted pairs
for (int i = 0; i < arr.length; i++) {
arr[i] = paired.get(i)[1];
}
}
// Driver code
public static void main(String[] args) {
int[] arr = {10, 11, 12};
int[] index = {1, 0, 2};
reorderArray(arr, index);
// Print the updated array
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
}
}
Python
# Python program to reorder arr[] using index[]
# using Naive approach
def reorderArray(arr, index):
# Pair each element with its target index
paired = []
for i in range(len(arr)):
paired.append([index[i], arr[i]])
# Sort the pairs by index
paired.sort()
# Rearrange arr based on sorted pairs
for i in range(len(arr)):
arr[i] = paired[i][1]
# Driver code
if __name__ == "__main__":
arr = [10, 11, 12]
index = [1, 0, 2]
reorderArray(arr, index)
# Print the updated array
print(" ".join(map(str, arr)))
C#
// C# program to reorder arr[] using index[]
// using Naive approach
using System;
using System.Collections.Generic;
class GfG {
// Function to reorder arr based on index
static void reorderArray(int[] arr, int[] index) {
// Pair each element with its target index
List<int[]> paired = new List<int[]>();
for (int i = 0; i < arr.Length; i++) {
paired.Add(new int[] { index[i], arr[i] });
}
// Sort the pairs by index
paired.Sort((a, b) => a[0].CompareTo(b[0]));
// Rearrange arr based on sorted pairs
for (int i = 0; i < arr.Length; i++) {
arr[i] = paired[i][1];
}
}
// Driver code
public static void Main() {
int[] arr = {10, 11, 12};
int[] index = {1, 0, 2};
reorderArray(arr, index);
// Print the updated array
for (int i = 0; i < arr.Length; i++) {
Console.Write(arr[i] + " ");
}
}
}
JavaScript
// JavaScript program to reorder arr[] using index[]
// using Naive approach
function reorderArray(arr, index) {
// Pair each element with its target index
let paired = [];
for (let i = 0; i < arr.length; i++) {
paired.push([index[i], arr[i]]);
}
// Sort the pairs by index
paired.sort((a, b) => a[0] - b[0]);
// Rearrange arr based on sorted pairs
for (let i = 0; i < arr.length; i++) {
arr[i] = paired[i][1];
}
}
// Driver code
let arr = [10, 11, 12];
let index = [1, 0, 2];
reorderArray(arr, index);
// Print the updated array
console.log(arr.join(" "));
[Better Approach] Using an Auxiliary Array - O(n) Time and O(n) Space
The idea is to reorder using an auxiliary array to temporarily hold the reordered elements by placing each element at the target index. Afterward, the reordered values are copied back into the original arr[].
C++
// C++ program to reorder arr[] using index[]
// using Auxiliary Array approach
#include <bits/stdc++.h>
using namespace std;
// Function to reorder arr based on index
void reorderArray(vector<int> &arr,
vector<int> &index) {
// Create an auxiliary array to hold
// the reordered elements
vector<int> reordered(arr.size());
// Place each element from arr[] at
// the position specified in index[]
for (int i = 0; i < arr.size(); i++) {
reordered[index[i]] = arr[i];
}
// Copy the reordered array back to arr[]
for (int i = 0; i < arr.size(); i++) {
arr[i] = reordered[i];
}
}
// Driver code
int main() {
vector<int> arr = {10, 11, 12};
vector<int> index = {1, 0, 2};
reorderArray(arr, index);
// Print the updated array
for (int i = 0; i < arr.size(); i++) {
cout << arr[i] << " ";
}
return 0;
}
Java
// Java program to reorder arr[] using index[]
// using Auxiliary Array approach
class GfG {
// Function to reorder arr based on index
static void reorderArray(int[] arr, int[] index) {
// Create an auxiliary array to hold
// the reordered elements
int[] reordered = new int[arr.length];
// Place each element from arr[] at
// the position specified in index[]
for (int i = 0; i < arr.length; i++) {
reordered[index[i]] = arr[i];
}
// Copy the reordered array back to arr[]
for (int i = 0; i < arr.length; i++) {
arr[i] = reordered[i];
}
}
// Driver code
public static void main(String[] args) {
int[] arr = {10, 11, 12};
int[] index = {1, 0, 2};
reorderArray(arr, index);
// Print the updated array
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
}
}
Python
# Python program to reorder arr[] using index[]
# using Auxiliary Array approach
# Function to reorder arr based on index
def reorderArray(arr, index):
# Create an auxiliary array to hold
# the reordered elements
reordered = [0] * len(arr)
# Place each element from arr[] at
# the position specified in index[]
for i in range(len(arr)):
reordered[index[i]] = arr[i]
# Copy the reordered array back to arr[]
for i in range(len(arr)):
arr[i] = reordered[i]
# Driver code
if __name__ == "__main__":
arr = [10, 11, 12]
index = [1, 0, 2]
reorderArray(arr, index)
# Print the updated array
for i in range(len(arr)):
print(arr[i], end=' ')
C#
// C# program to reorder arr[] using index[]
// using Auxiliary Array approach
using System;
class GfG {
// Function to reorder arr based on index
static void reorderArray(int[] arr, int[] index) {
// Create an auxiliary array to hold
// the reordered elements
int[] reordered = new int[arr.Length];
// Place each element from arr[] at
// the position specified in index[]
for (int i = 0; i < arr.Length; i++) {
reordered[index[i]] = arr[i];
}
// Copy the reordered array back to arr[]
for (int i = 0; i < arr.Length; i++) {
arr[i] = reordered[i];
}
}
// Driver code
public static void Main() {
int[] arr = {10, 11, 12};
int[] index = {1, 0, 2};
reorderArray(arr, index);
// Print the updated array
for (int i = 0; i < arr.Length; i++) {
Console.Write(arr[i] + " ");
}
}
}
JavaScript
// JavaScript program to reorder arr[] using index[]
// using Auxiliary Array approach
// Function to reorder arr based on index
function reorderArray(arr, index) {
// Create an auxiliary array to hold
// the reordered elements
let reordered = new Array(arr.length);
// Place each element from arr[] at
// the position specified in index[]
for (let i = 0; i < arr.length; i++) {
reordered[index[i]] = arr[i];
}
// Copy the reordered array back to arr[]
for (let i = 0; i < arr.length; i++) {
arr[i] = reordered[i];
}
}
// Driver code
let arr = [10, 11, 12];
let index = [1, 0, 2];
reorderArray(arr, index);
// Print the updated array
for (let i = 0; i < arr.length; i++) {
process.stdout.write(arr[i] + " ");
}
[Expected Approach - 1] Using Cyclic Sort - O(n) Time and O(1) Space
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.
Steps to implement the above idea:
- Start a while loop with variable i = 0 and continue until i < length(arr), to process every element.
- For each element, check if it's already in the correct position using index[i] == i to avoid unnecessary swaps.
- If it is, just increment i to proceed to the next position, as the current one is already placed correctly.
- If not, perform a manual swap of arr[i] and arr[index[i]] using a temporary variable to avoid data loss.
- Alongside, manually swap index[i] with index[index[i]] to maintain synchronization between the index and value arrays.
- Repeat this process until all elements are at their correct index according to the index[] array, ensuring correctness.
- Once the loop completes, print the final reordered arr[] which now matches the intended layout defined by index[].
C++
// C++ program to reorder arr[] using index[]
// using Cyclic Sort approach
#include <bits/stdc++.h>
using namespace std;
// Function to reorder arr based on index
void reorderArray(vector<int> &arr,
vector<int> &index) {
int i = 0;
// Perform cyclic swaps until all elements
// are placed at their correct index
while (i < arr.size()) {
// If current index is already
// correct, move on
if (index[i] == i) {
i++;
}
// Otherwise, swap arr[i] with arr[index[i]]
// and update index[i] accordingly
else {
swap(arr[i], arr[index[i]]);
swap(index[i], index[index[i]]);
}
}
}
// Driver code
int main() {
vector<int> arr = {10, 11, 12};
vector<int> index = {1, 0, 2};
reorderArray(arr, index);
// Print the updated array
for (int i = 0; i < arr.size(); i++) {
cout << arr[i] << " ";
}
return 0;
}
Java
// Java program to reorder arr[] using index[]
// using Cyclic Sort approach
class GfG {
// Function to reorder arr based on index
static void reorderArray(int[] arr, int[] index) {
int i = 0;
// Perform cyclic swaps until all elements
// are placed at their correct index
while (i < arr.length) {
// If current index is already
// correct, move on
if (index[i] == i) {
i++;
}
// Otherwise, swap arr[i] with arr[index[i]]
// and update index[i] accordingly
else {
int temp1 = arr[i];
arr[i] = arr[index[i]];
arr[index[i]] = temp1;
int temp2 = index[i];
index[i] = index[temp2];
index[temp2] = temp2;
}
}
}
// Driver code
public static void main(String[] args) {
int[] arr = {10, 11, 12};
int[] index = {1, 0, 2};
reorderArray(arr, index);
// Print the updated array
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
}
}
Python
# Python program to reorder arr[] using index[]
# using Cyclic Sort approach
def reorderArray(arr, index):
i = 0
# Perform cyclic swaps until all elements
# are placed at their correct index
while i < len(arr):
# If current index is already
# correct, move on
if index[i] == i:
i += 1
# Otherwise, swap arr[i] with arr[index[i]]
# and update index[i] accordingly
else:
temp1 = arr[i]
arr[i] = arr[index[i]]
arr[index[i]] = temp1
temp2 = index[i]
index[i] = index[temp2]
index[temp2] = temp2
# Driver code
if __name__ == "__main__":
arr = [10, 11, 12]
index = [1, 0, 2]
reorderArray(arr, index)
# Print the updated array
for i in range(len(arr)):
print(arr[i], end=' ')
C#
// C# program to reorder arr[] using index[]
// using Cyclic Sort approach
using System;
class GfG {
// Function to reorder arr based on index
public static void reorderArray(int[] arr, int[] index) {
int i = 0;
// Perform cyclic swaps until all elements
// are placed at their correct index
while (i < arr.Length) {
// If current index is already
// correct, move on
if (index[i] == i) {
i++;
}
// Otherwise, swap arr[i] with arr[index[i]]
// and update index[i] accordingly
else {
int temp1 = arr[i];
arr[i] = arr[index[i]];
arr[index[i]] = temp1;
int temp2 = index[i];
index[i] = index[temp2];
index[temp2] = temp2;
}
}
}
// Driver code
public static void Main() {
int[] arr = {10, 11, 12};
int[] index = {1, 0, 2};
reorderArray(arr, index);
// Print the updated array
for (int i = 0; i < arr.Length; i++) {
Console.Write(arr[i] + " ");
}
}
}
JavaScript
// JavaScript program to reorder arr[] using index[]
// using Cyclic Sort approach
function reorderArray(arr, index) {
let i = 0;
// Perform cyclic swaps until all elements
// are placed at their correct index
while (i < arr.length) {
// If current index is already
// correct, move on
if (index[i] === i) {
i++;
}
// Otherwise, swap arr[i] with arr[index[i]]
// and update index[i] accordingly
else {
let temp1 = arr[i];
arr[i] = arr[index[i]];
arr[index[i]] = temp1;
let temp2 = index[i];
index[i] = index[temp2];
index[temp2] = temp2;
}
}
}
// Driver code
let arr = [10, 11, 12];
let index = [1, 0, 2];
reorderArray(arr, index);
// Print the updated array
for (let i = 0; i < arr.length; i++) {
process.stdout.write(arr[i] + " ");
}
[Expected Approach - 2] Using Mathematics - O(n) Time and O(1) Space
The idea is to reorder elements in-place without using extra space by encoding two numbers (original and new) into a single number. Since each element in arr[] is less than or equal to the maximum value, we pick value = max + 1 to ensure uniqueness when combining.
We update arr[index[i]] using -> arr[index[i]] += (arr[i] % value) * value, which embeds both current and new values in the same cell.
- The % value ensures we use the original value even after updates.
- The * value shifts the new value to a higher place (like storing digits).
In the final step, dividing every element by value removes the original part and leaves only the reordered value
C++
// C++ program to reorder arr[] using index[]
// using Mathematical Encoding
#include <bits/stdc++.h>
using namespace std;
// Function to reorder arr based on index
void reorderArray(vector<int> &arr,
vector<int> &index) {
int n = arr.size();
// Find the maximum value
int maxVal = arr[0];
for (int i = 1; i < n; i++) {
if (arr[i] > maxVal) {
maxVal = arr[i];
}
}
// Set value as max + 1
int value = maxVal + 1;
// Encode both old and new
// values at index[i]
for (int i = 0; i < n; i++) {
arr[index[i]] += (arr[i] % value) * value;
}
// Decode to get the reordered values
for (int i = 0; i < n; i++) {
arr[i] = arr[i] / value;
}
}
// Driver code
int main() {
vector<int> arr = {10, 11, 12};
vector<int> index = {1, 0, 2};
reorderArray(arr, index);
// Print the updated array
for (int i = 0; i < arr.size(); i++) {
cout << arr[i] << " ";
}
return 0;
}
Java
// Java program to reorder arr[] using index[]
// using Mathematical Encoding
class GfG {
// Function to reorder arr based on index
static void reorderArray(int[] arr, int[] index) {
int n = arr.length;
// Find the maximum value
int maxVal = arr[0];
for (int i = 1; i < n; i++) {
if (arr[i] > maxVal) {
maxVal = arr[i];
}
}
// Set value as max + 1
int value = maxVal + 1;
// Encode both old and new
// values at index[i]
for (int i = 0; i < n; i++) {
arr[index[i]] += (arr[i] % value) * value;
}
// Decode to get the reordered values
for (int i = 0; i < n; i++) {
arr[i] = arr[i] / value;
}
}
// Driver code
public static void main(String[] args) {
int[] arr = {10, 11, 12};
int[] index = {1, 0, 2};
reorderArray(arr, index);
// Print the updated array
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
}
}
Python
# Python program to reorder arr[] using index[]
# using Mathematical Encoding
def reorderArray(arr, index):
n = len(arr)
# Find the maximum value
maxVal = arr[0]
for i in range(1, n):
if arr[i] > maxVal:
maxVal = arr[i]
# Set value as max + 1
value = maxVal + 1
# Encode both old and new
# values at index[i]
for i in range(n):
arr[index[i]] += (arr[i] % value) * value
# Decode to get the reordered values
for i in range(n):
arr[i] = arr[i] // value
# Driver code
if __name__ == "__main__":
arr = [10, 11, 12]
index = [1, 0, 2]
reorderArray(arr, index)
# Print the updated array
for i in range(len(arr)):
print(arr[i], end=' ')
C#
// C# program to reorder arr[] using index[]
// using Mathematical Encoding
using System;
class GfG {
// Function to reorder arr based on index
public static void reorderArray(int[] arr,
int[] index) {
int n = arr.Length;
// Find the maximum value
int maxVal = arr[0];
for (int i = 1; i < n; i++) {
if (arr[i] > maxVal) {
maxVal = arr[i];
}
}
// Set value as max + 1
int value = maxVal + 1;
// Encode both old and new
// values at index[i]
for (int i = 0; i < n; i++) {
arr[index[i]] += (arr[i] % value) * value;
}
// Decode to get the reordered values
for (int i = 0; i < n; i++) {
arr[i] = arr[i] / value;
}
}
// Driver code
public static void Main() {
int[] arr = {10, 11, 12};
int[] index = {1, 0, 2};
reorderArray(arr, index);
// Print the updated array
for (int i = 0; i < arr.Length; i++) {
Console.Write(arr[i] + " ");
}
}
}
JavaScript
// JavaScript program to reorder arr[] using index[]
// using Mathematical Encoding
function reorderArray(arr, index) {
let n = arr.length;
// Find the maximum value
let maxVal = arr[0];
for (let i = 1; i < n; i++) {
if (arr[i] > maxVal) {
maxVal = arr[i];
}
}
// Set value as max + 1
let value = maxVal + 1;
// Encode both old and new
// values at index[i]
for (let i = 0; i < n; i++) {
arr[index[i]] += (arr[i] % value) * value;
}
// Decode to get the reordered values
for (let i = 0; i < n; i++) {
arr[i] = Math.floor(arr[i] / value);
}
}
// Driver code
let arr = [10, 11, 12];
let index = [1, 0, 2];
reorderArray(arr, index);
// Print the updated array
for (let i = 0; i < arr.length; i++) {
process.stdout.write(arr[i] + " ");
}
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem