If you have no duplicate numbers in the second array like the provided example, you can use Map
.
At first, take a map. Put array2 values into key
and array1 values into value
in the map. Then sort the map according to the values. Now if you get the keys from the map, you'll get what you want.
Use TreeMap. It doesn't need sorting. It enters data such way that guarantees that the map will be in ascending key order.
Map<Integer, Integer> m = new TreeMap<>();
int[] arr1 = {1, 2, 3, 4, 5};
int[] arr2 = {3, 6, 5, 1, 9};
// Put array2 values as key parameter and array1 values as value parameter
for (int i = 0; i < arr1.length; i++) {
m.put(arr2[i], arr1[i]);
}
int i = 0;
// Print the sorted map
for (Map.Entry<Integer, Integer> entry : m.entrySet()) {
System.out.println("arr1["+ i +"] = " + entry.getValue());
i++;
}
Output:
arr1[0] = 4
arr1[1] = 1
arr1[2] = 3
arr1[3] = 2
arr1[4] = 5