Program to Sort an array according to the order defined by another array is discussed here. Given two arrays A [] and B [], sort A in such a way that the relative order among the elements will be the same as those are in B. The elements in array A has to be printed according to the sequence of order of elements specified in array B, the rest of the elements, remaining in array A are printed at the end.
Method 1: Traverse array 2 elements and check if those elements are found in array 1. Perform a binary search to find the elements. If array 2 elements are found in array 1, print them. Print all the remaining elements from array 1 at the end.
Method 2: Store all the array 1 elements in a hashmap. Then, traverse array 2 and check if the element is present in the map. If present, print the element k number of times where k is the frequency of appearance of the element. Then, print the remaining elements of array 1.
For example,
Array A [] = {3, 6, 13, 3, 9, 10, 14, 6, 9, 13}
Array B[] = {6, 3, 9, 13, 10}
Output: {6, 6, 3, 3, 9, 9, 13, 13, 10, 14}
@@coding::1@@
@@coding::2@@
Recommended Programs