Saturday, October 14, 2017

Given two arrays (of same length), of which 2nd array contains indices in random order(0 to n-1), replace array with their indexed element values

Q: http://www.geeksforgeeks.org/reorder-a-array-according-to-given-indexes/

Program:

import java.util.Arrays;

class ReplaceWithIndexEle {
        static public void process(int[] ar, int[] ind) {
                for(int i=0; i<ar.length; i++) {
                        int index = ind[i];

                        while(index < i) {
                                index = ind[index];
                        }

                        int temp = ar[i];
                        ar[i] = ar[index];
                        ar[index] = temp;
                }
        }

        static public void main(String[] args) {
                int[] ar = {20, 15, 12, 5, 9, 3, 8, 1};
                int[] ind = {4, 2, 7, 0, 6, 1, 5, 3};

                System.out.println(Arrays.toString(ar));
                process(ar, ind);
                System.out.println(Arrays.toString(ar));
        }
}