Reorder array using given indexes in C

Reorder array using given indexes 

Given two input arrays of same size, second array is index array, we need to reorder array using given indexes array.

Example: n = 4

                  Arr[4]={4, 2, 1, 3}

                  Idx[4]={3, 2, 0, 1}

                  Output : Arr[4]={1, 3, 2, 4}

Reorder array using given indexes in C

Algorithm :

 

  • Take the size of the array from the user and store it in variable n.
  • Declare two arrays arr[] and idx[], one for array elements and another to store the require indexes value.
  • Take the elements of the both arrays from the user.
  • Declare an another array for the output say, res[].
  • Traverse the result array and set,  res[idx[i]]=arr[].

C code based on above algorithm

#include<stdio.h>

void reorder(int arr[], int idx[], int n, int res[])
{
for(int i=0; i<n; i++)
{
res[idx[i]] = arr[i];
}
}

int main()
{

int n;
scanf("%d", &n);

int arr[n], idx[n];

for(int i=0; i<n; i++)
scanf("%d", &arr[i]);

for(int i=0; i<n; i++)
scanf("%d", &idx[i]);


int res[n];
reorder(arr, idx, n, res);

printf("Array after merging\n");
for (int i=0; i < n; i++)
printf("%d ", res[i]);

return 0;
}
Input :

4

4 2 1 3

1 3 0 2

Output :

1 4 3 2