Reorder an array according to given indexes - GeeksforGeeks
Given two integer arrays of same size, "arr[]" and "index[]", reorder elements in "arr[]" according to given index array. It is not allowed to given array arr's length.
Read full article from Reorder an array according to given indexes - GeeksforGeeks
Given two integer arrays of same size, "arr[]" and "index[]", reorder elements in "arr[]" according to given index array. It is not allowed to given array arr's length.
Input: arr[] = [10, 11, 12]; index[] = [1, 0, 2]; Output: arr[] = [11, 10, 12] index[] = [0, 1, 2]
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;
}
}
}
A Simple Solution 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[]. Finally copy temp[] to arr[] and set all values of index[i] as i.
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;
}
}