Fundamentals/Relative Sort Array
← PrevNext →
Given two integer arrays arr1 and arr2, sort arr1 so its elements appear in the same relative order as in arr2. Elements of arr1 not present in arr2 are placed at the end in ascending order.
Input
arr1: array of integers to sort
arr2: array defining the priority order
Output
A new array containing the elements of arr1 reordered as described.
Examples
Example 1
Inputarr1 = [2, 3, 1, 3, 2, 4, 6, 7, 9, 2, 19], arr2 = [2, 1, 4, 3, 9, 6]
Output[2, 2, 2, 1, 4, 3, 3, 9, 6, 7, 19]
Example 2
Inputarr1 = [28, 6, 22, 8, 44, 17], arr2 = [22, 28, 8, 6]
Output[22, 28, 8, 6, 17, 44]
Explanation: 17 and 44 are absent from arr2, so they trail in ascending order.
Constraints
All elements of arr2 are distinct.
Elements may repeat in arr1.