Open In App

Sort an array according to the order defined by another array

Last Updated : 16 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Given two arrays A1[] and A2[], sort A1 in such a way that the relative order among the elements will be same as those are in A2. For the elements not present in A2, append them at last in sorted order. 

Example: 

Input: A1[] = {2, 1, 2, 5, 7, 1, 9, 3, 6, 8, 8}
           A2[] = {2, 1, 8, 3}
Output: A1[] = {2, 2, 1, 1, 8, 8, 3, 5, 6, 7, 9}

Input: A1[] = {4, 5, 1, 1, 3, 2}
           A2[] = {3, 1}
Output: A1[] = {3, 1, 1, 2, 4, 5}

We strongly recommend that you click here and practice it, before moving on to the solution.

Sort an array according to the order defined by another array using Sorting and Binary Search:

The idea is to sort the A1[] array and then according to A2[] store the elements.

Let the size of A1[] be m and the size of A2[] be n. 

  • Create a temporary array temp of size m and copy the contents of A1[] to it.
  • Create another array visited[] and initialize all entries in it as false. visited[] is used to mark those elements in temp[] which are copied to A1[].
  • Sort temp[]
  • Initialize the output index ind as 0.
  • Do following for every element of A2[i] in A2[] 
    • Binary search for all occurrences of A2[i] in temp[], if present then copy all occurrences to A1[ind] and increment ind. Also mark the copied elements visited[]
  • Copy all unvisited elements from temp[] to A1[]


Below image is a dry run of the above approach:

Below is the implementation of the above approach: 

C++
// A C++ program to sort an array according to the order
// defined by another array
#include <bits/stdc++.h>
using namespace std;

// A Binary Search based function to find index of FIRST
// occurrence of x in arr[].  If x is not present, then it
// returns -1

// The same can be done using the lower_bound
// function in C++ STL
int first(int arr[], int low, int high, int x, int n)
{

    // Checking condition
    if (high >= low) {

        // FInd the mid element
        int mid = low + (high - low) / 2;

        // Check if the element is the extreme left
        // in the left half of the array
        if ((mid == 0 || x > arr[mid - 1]) && arr[mid] == x)
            return mid;

        // If the element lies on the right half
        if (x > arr[mid])
            return first(arr, (mid + 1), high, x, n);

        // Check for element in the left half
        return first(arr, low, (mid - 1), x, n);
    }

    // ELement not found
    return -1;
}

// Sort A1[0..m-1] according to the order defined by
// A2[0..n-1].
void sortAccording(int A1[], int A2[], int m, int n)
{
    // The temp array is used to store a copy of A1[] and
    // visited[] is used mark the visited elements in
    // temp[].
    int temp[m], visited[m];
    for (int i = 0; i < m; i++) {
        temp[i] = A1[i];
        visited[i] = 0;
    }

    // Sort elements in temp
    sort(temp, temp + m);

    // for index of output which is sorted A1[]
    int ind = 0;

    // Consider all elements of A2[], find them in temp[]
    // and copy to A1[] in order.
    for (int i = 0; i < n; i++) {
        // Find index of the first occurrence of A2[i] in
        // temp
        int f = first(temp, 0, m - 1, A2[i], m);

        // If not present, no need to proceed
        if (f == -1)
            continue;

        // Copy all occurrences of A2[i] to A1[]
        for (int j = f; (j < m && temp[j] == A2[i]); j++) {
            A1[ind++] = temp[j];
            visited[j] = 1;
        }
    }

    // Now copy all items of temp[]
    // which are not present in A2[]
    for (int i = 0; i < m; i++)
        if (visited[i] == 0)
            A1[ind++] = temp[i];
}

// Utility function to print an array
void printArray(int arr[], int n)
{

    // Iterate in the array
    for (int i = 0; i < n; i++)
        cout << arr[i] << " ";
    cout << endl;
}

// Driver Code
int main()
{
    int A1[] = { 2, 1, 2, 5, 7, 1, 9, 3, 6, 8, 8 };
    int A2[] = { 2, 1, 8, 3 };
    int m = sizeof(A1) / sizeof(A1[0]);
    int n = sizeof(A2) / sizeof(A2[0]);

    // Prints the sorted array
    cout << "Sorted array is \n";
    sortAccording(A1, A2, m, n);
    printArray(A1, m);
    return 0;
}
Java
// A JAVA program to sort an array according
// to the order defined by another array
import java.io.*;
import java.util.Arrays;

class GFG {

    /* A Binary Search based function to find
    index of FIRST occurrence of x in arr[].
    If x is not present, then it returns -1 */
    static int first(int arr[], int low, int high, int x,
                     int n)
    {
        if (high >= low) {
            /* (low + high)/2; */
            int mid = low + (high - low) / 2;

            if ((mid == 0 || x > arr[mid - 1])
                && arr[mid] == x)
                return mid;
            if (x > arr[mid])
                return first(arr, (mid + 1), high, x, n);
            return first(arr, low, (mid - 1), x, n);
        }
        return -1;
    }

    // Sort A1[0..m-1] according to the order
    // defined by A2[0..n-1].
    static void sortAccording(int A1[], int A2[], int m,
                              int n)
    {
        // The temp array is used to store a copy
        // of A1[] and visited[] is used to mark the
        // visited elements in temp[].
        int temp[] = new int[m], visited[] = new int[m];
        for (int i = 0; i < m; i++) {
            temp[i] = A1[i];
            visited[i] = 0;
        }

        // Sort elements in temp
        Arrays.sort(temp);

        // for index of output which is sorted A1[]
        int ind = 0;

        // Consider all elements of A2[], find them
        // in temp[] and copy to A1[] in order.
        for (int i = 0; i < n; i++) {
            // Find index of the first occurrence
            // of A2[i] in temp
            int f = first(temp, 0, m - 1, A2[i], m);

            // If not present, no need to proceed
            if (f == -1)
                continue;

            // Copy all occurrences of A2[i] to A1[]
            for (int j = f; (j < m && temp[j] == A2[i]);
                 j++) {
                A1[ind++] = temp[j];
                visited[j] = 1;
            }
        }

        // Now copy all items of temp[] which are
        // not present in A2[]
        for (int i = 0; i < m; i++)
            if (visited[i] == 0)
                A1[ind++] = temp[i];
    }

    // Utility function to print an array
    static void printArray(int arr[], int n)
    {
        for (int i = 0; i < n; i++)
            System.out.print(arr[i] + " ");
        System.out.println();
    }

    // Driver program to test above function.
    public static void main(String args[])
    {
        int A1[] = { 2, 1, 2, 5, 7, 1, 9, 3, 6, 8, 8 };
        int A2[] = { 2, 1, 8, 3 };
        int m = A1.length;
        int n = A2.length;
        System.out.println("Sorted array is ");
        sortAccording(A1, A2, m, n);
        printArray(A1, m);
    }
}

/*This code is contributed by Nikita Tiwari.*/
Python3
"""A Python 3  program to sort an array 
according to the order defined by 
another array"""

"""A Binary Search based function to find 
index of FIRST occurrence of x in arr[].
If x is not present, then it returns -1 """


def first(arr, low, high, x, n):
    if (high >= low):
        mid = low + (high - low) // 2  # (low + high)/2
        if ((mid == 0 or x > arr[mid-1]) and arr[mid] == x):
            return mid
        if (x > arr[mid]):
            return first(arr, (mid + 1), high, x, n)
        return first(arr, low, (mid - 1), x, n)

    return -1

# Sort A1[0..m-1] according to the order
# defined by A2[0..n-1].


def sortAccording(A1, A2, m, n):
    """The temp array is used to store a copy
    of A1[] and visited[] is used mark the 
    visited elements in temp[]."""
    temp = [0] * m
    visited = [0] * m

    for i in range(0, m):
        temp[i] = A1[i]
        visited[i] = 0

    # Sort elements in temp
    temp.sort()

    # for index of output which is sorted A1[]
    ind = 0

    """Consider all elements of A2[], find
    them in temp[] and copy to A1[] in order."""
    for i in range(0, n):

        # Find index of the first occurrence
        # of A2[i] in temp
        f = first(temp, 0, m-1, A2[i], m)

        # If not present, no need to proceed
        if (f == -1):
            continue

        # Copy all occurrences of A2[i] to A1[]
        j = f
        while (j < m and temp[j] == A2[i]):
            A1[ind] = temp[j]
            ind = ind + 1
            visited[j] = 1
            j = j + 1

    # Now copy all items of temp[] which are
    # not present in A2[]
    for i in range(0, m):
        if (visited[i] == 0):
            A1[ind] = temp[i]
            ind = ind + 1

# Utility function to print an array


def printArray(arr, n):
    for i in range(0, n):
        print(arr[i], end=" ")
    print("")


# Driver program to test above function.
A1 = [2, 1, 2, 5, 7, 1, 9, 3, 6, 8, 8]
A2 = [2, 1, 8, 3]
m = len(A1)
n = len(A2)
print("Sorted array is ")
sortAccording(A1, A2, m, n)
printArray(A1, m)


# This code is contributed by Nikita Tiwari.
C#
// A C# program to sort an array according
// to the order defined by another array
using System;

class GFG {

    /* A Binary Search based function to find
    index of FIRST occurrence of x in arr[].
    If x is not present, then it returns -1 */
    static int first(int[] arr, int low, int high, int x,
                     int n)
    {
        if (high >= low) {
            /* (low + high)/2; */
            int mid = low + (high - low) / 2;

            if ((mid == 0 || x > arr[mid - 1])
                && arr[mid] == x)
                return mid;
            if (x > arr[mid])
                return first(arr, (mid + 1), high, x, n);
            return first(arr, low, (mid - 1), x, n);
        }
        return -1;
    }

    // Sort A1[0..m-1] according to the order
    // defined by A2[0..n-1].
    static void sortAccording(int[] A1, int[] A2, int m,
                              int n)
    {

        // The temp array is used to store a copy
        // of A1[] and visited[] is used to mark
        // the visited elements in temp[].
        int[] temp = new int[m];
        int[] visited = new int[m];

        for (int i = 0; i < m; i++) {
            temp[i] = A1[i];
            visited[i] = 0;
        }

        // Sort elements in temp
        Array.Sort(temp);

        // for index of output which is
        // sorted A1[]
        int ind = 0;

        // Consider all elements of A2[], find
        // them in temp[] and copy to A1[] in
        // order.
        for (int i = 0; i < n; i++) {

            // Find index of the first occurrence
            // of A2[i] in temp
            int f = first(temp, 0, m - 1, A2[i], m);

            // If not present, no need to proceed
            if (f == -1)
                continue;

            // Copy all occurrences of A2[i] to A1[]
            for (int j = f; (j < m && temp[j] == A2[i]);
                 j++) {
                A1[ind++] = temp[j];
                visited[j] = 1;
            }
        }

        // Now copy all items of temp[] which are
        // not present in A2[]
        for (int i = 0; i < m; i++)
            if (visited[i] == 0)
                A1[ind++] = temp[i];
    }

    // Utility function to print an array
    static void printArray(int[] arr, int n)
    {
        for (int i = 0; i < n; i++)
            Console.Write(arr[i] + " ");
        Console.WriteLine();
    }

    // Driver program to test above function.
    public static void Main()
    {
        int[] A1 = { 2, 1, 2, 5, 7, 1, 9, 3, 6, 8, 8 };
        int[] A2 = { 2, 1, 8, 3 };
        int m = A1.Length;
        int n = A2.Length;
        Console.WriteLine("Sorted array is ");
        sortAccording(A1, A2, m, n);
        printArray(A1, m);
    }
}

// This code is contributed by nitin mittal.
Javascript
<script>

// A JavaScript program to sort an array according
// to the order defined by another array

    /* A Binary Search based function to find
    index of FIRST occurrence of x in arr[].
    If x is not present, then it returns -1 */
    function first(arr,low,high,x,n)
    {
        if (high >= low) {
            // (low + high)/2; 
            let mid = low + Math.floor((high - low) / 2);
 
            if ((mid == 0 || x > arr[mid - 1]) && arr[mid] == x)
                return mid;
            if (x > arr[mid])
                return first(arr, (mid + 1), high,x, n);
            return first(arr, low, (mid - 1), x, n);
        }
        return -1;
    }
    
    // Sort A1[0..m-1] according to the order
    // defined by A2[0..n-1].
    function sortAccording(A1,A2,m,n)
    {
        // The temp array is used to store a copy
        // of A1[] and visited[] is used to mark the
        // visited elements in temp[].
        let temp=[];
        let visited=[];
        
        for (let i = 0; i < m; i++)
        {
            temp[i] = A1[i];
            visited[i] = 0;
        }
        
        // Sort elements in temp
        temp.sort(function(a, b){return a-b});
        
        // for index of output which is sorted A1[]
        let ind = 0;
        
        // Consider all elements of A2[], find them
        // in temp[] and copy to A1[] in order.
        for (let i = 0; i < n; i++)
        {
            // Find index of the first occurrence
            // of A2[i] in temp
            let f = first(temp, 0, m - 1, A2[i], m);
            // If not present, no need to proceed
            if (f == -1)
            {
                continue;
            }
            // Copy all occurrences of A2[i] to A1[]
            for (let j = f; (j < m && temp[j] == A2[i]);j++)
            {
                A1[ind++] = temp[j];
                visited[j] = 1;
            }
        }
        // Now copy all items of temp[] which are
        // not present in A2[]
        for (let i = 0; i < m; i++)
        {
            if (visited[i] == 0)
                A1[ind++] = temp[i];
        }
        
    }
    
    // Utility function to print an array
    function printArray(arr,n)
    {
        for (let i = 0; i < n; i++)
        {
            document.write(arr[i] + " ");
            
        }
        document.write("<br>");
    }
    
    // Driver program to test above function.
    let A1=[2, 1, 2, 5, 7, 1, 9, 3, 6, 8, 8 ];
    let A2=[2, 1, 8, 3 ];
    
    let m = A1.length;
    let n = A2.length;
    document.write("Sorted array is <br>");
    
    sortAccording(A1, A2, m, n);
    printArray(A1, m);
    
    // This code is contributed by avanitrachhadiya2155
    
</script>
PHP
<?php 
// A PHP program to sort an array according 
// to the order defined by another array

/* A Binary Search based function to find index 
of FIRST occurrence of x in arr[]. If x is not 
present, then it returns -1 */
function first(&$arr, $low, $high, $x, $n)
{
    if ($high >= $low)
    {
        $mid = intval($low + ($high - $low) / 2); 
        if (($mid == 0 || $x > $arr[$mid - 1]) && 
                               $arr[$mid] == $x)
            return $mid;
        if ($x > $arr[$mid])
            return first($arr, ($mid + 1), $high, $x, $n);
        return first($arr, $low, ($mid - 1), $x, $n);
    }
    return -1;
}

// Sort A1[0..m-1] according to the order 
// defined by A2[0..n-1].
function sortAccording(&$A1, &$A2, $m, $n)
{
    // The temp array is used to store a copy 
    // of A1[] and visited[] is used mark the
    // visited elements in temp[].
    $temp = array_fill(0, $m, NULL);
    $visited = array_fill(0, $m, NULL);
    for ($i = 0; $i < $m; $i++)
    {
        $temp[$i] = $A1[$i];
        $visited[$i] = 0;
    }

    // Sort elements in temp
    sort($temp);

    $ind = 0; // for index of output which is sorted A1[]

    // Consider all elements of A2[], find 
    // them in temp[] and copy to A1[] in order.
    for ($i = 0; $i < $n; $i++)
    {
        // Find index of the first occurrence
        // of A2[i] in temp
        $f = first($temp, 0, $m - 1, $A2[$i], $m);

        // If not present, no need to proceed
        if ($f == -1) continue;

        // Copy all occurrences of A2[i] to A1[]
        for ($j = $f; ($j < $m && 
             $temp[$j] == $A2[$i]); $j++)
        {
            $A1[$ind++] = $temp[$j];
            $visited[$j] = 1;
        }
    }

    // Now copy all items of temp[] which
    // are not present in A2[]
    for ($i = 0; $i < $m; $i++)
        if ($visited[$i] == 0)
            $A1[$ind++] = $temp[$i];
}

// Utility function to print an array
function printArray(&$arr, $n)
{
    for ($i = 0; $i < $n; $i++)
        echo $arr[$i] . " ";
    echo "\n";
}

// Driver Code
$A1 = array(2, 1, 2, 5, 7, 1, 9, 3, 6, 8, 8);
$A2 = array(2, 1, 8, 3);
$m = sizeof($A1);
$n = sizeof($A2);
echo "Sorted array is \n";
sortAccording($A1, $A2, $m, $n);
printArray($A1, $m);

// This code is contributed by ita_c
?>

Output
Sorted array is 
2 2 1 1 8 8 3 5 6 7 9 

Time complexity: O(M Log M + N Log M), Sorting Arr1[] of size M i.e M log M and searching of Arr2[] elements of size N in Arr1[] i.e N log M
Auxiliary Space: O(M), visited and temp array of size M for storing Arr1[].

Sort an array according to the order defined by another array using  Self-Balancing Binary Search Tree:

We can also use a self-balancing BST like AVL Tree, Red Black Tree, etc. Following are detailed steps. 

  • Create a self-balancing BST of all elements in A1[]. In every node of BST, also keep track of the count of occurrences of the key and a bool field visited which is initialized as false for all nodes.
  • Initialize the output index ind as 0.
  • Do the following for every element of A2[i] in A2[] 
    1. Search for A2[i] in the BST, if present then copy all occurrences to A1[ind] and increment ind. Also, mark the copied elements visited in the BST node.
  • Do an in-order traversal of BST and copy all unvisited keys to A1[].

Simplified implementation approach:

-> The above approach can be easily implemented by making use of the inbuilt Data structures of a programming language which makes use of these Self-Balancing Binary Search Trees.

-> For Ex. The TreeMap in Java makes uses of a Red-Black Tree to achieve the sorted insert thereby a sorted Traversal when needed as shown below.

C++
#include <iostream>
#include <map>
#include <vector>

using namespace std;

// Function to sort an array according to the order defined by another array
vector<int> sortA1ByA2(const vector<int>& A1, const vector<int>& A2) {
    // Create a map to store the frequency of elements in A1
    map<int, int> freqMap;
    for (int element : A1) {
        freqMap[element]++;
    }

    // Create a result vector to store the sorted elements
    vector<int> result;

    // Iterate over A2 and add elements from A1 to the result vector according to their frequency
    for (int element : A2) {
        int count = freqMap[element];
        while (count > 0) {
            result.push_back(element);
            count--;
        }
        freqMap.erase(element);
    }

    // Add any remaining elements from A1 to the result vector
    for (auto it = freqMap.begin(); it != freqMap.end(); ++it) {
        int count = it->second;
        while (count > 0) {
            result.push_back(it->first);
            count--;
        }
    }

    return result;
}

// Function to print an array
void printArray(const vector<int>& arr) {
    for (int element : arr) {
        cout << element << " ";
    }
    cout << endl;
}

int main() {
    vector<int> A1 = {2, 1, 2, 5, 7, 1, 9, 3, 6, 8, 8};
    vector<int> A2 = {2, 1, 8, 3};

    // Sort A1 according to A2
    vector<int> sortedArray = sortA1ByA2(A1, A2);

    // Print the sorted array
    cout << "Sorted array is: ";
    printArray(sortedArray);

    return 0;
}
Java
// A Java program to sort an array according to the order
// defined by another array

import java.io.*;
import java.util.*;

class Solution{
    // A1[] : the input array-1
    // M : size of the array A1[]
    // A2[] : the input array-2
    // N : size of the array A2[]
    
    //Function to sort an array according to the other array.
    public static int[] sortA1ByA2(int A1[], int M, int A2[], int N)
    {
        //TreeMap in Java internally uses a Red-Black Tree. 
        //Hence we are making use of this library implementation of RB Tree to solve the given problem.
        TreeMap<Integer, Integer> freqMap = new TreeMap<>();
        
        //Logic to store the frequency of elements of A1[]
        for(int i=0;i<M;i++){
            freqMap.put(A1[i] , 1 + freqMap.getOrDefault(A1[i], 0));
        }
        
        int[] result = new int[M];
        int index = 0;
        
        //Logic to sort the values of A1[] according to A2[] by finding, copying(to result array) & 
        //replacing from the constructed TreeMap.
        for(int i=0;i<N;i++){
            int size = freqMap.getOrDefault(A2[i] , 0);
            while(size > 0){
                result[index++] = A2[i];
                size--;
            }
            freqMap.remove(A2[i]);
        }
        
        //Logic to fetch & copy the remaining elements from the constructed TreeMap into the result array.
        for(int key : freqMap.keySet()){
            int size = freqMap.get(key);
            while(size > 0){
                result[index++] = key;
                size--;
            }
        }
        
        return result;
    }
  
   // Utility function to print an array
    static void printArray(int arr[], int n)
    {
        for (int i = 0; i < n; i++)
            System.out.print(arr[i] + " ");
        System.out.println();
    }
  
  // Driver code
    public static void main(String[] args)
    {
        int A1[] = { 2, 1, 2, 5, 7, 1, 9, 3, 6, 8, 8 };
        int A2[] = { 2, 1, 8, 3 };
        int m = A1.length;
        int n = A2.length;
 
        // The ans array is used to store the final sorted
        // array
        int ans[] = sortA1ByA2(A1, m, A2, n);
 
        System.out.println("Sorted array is ");
        printArray(ans, m);
    }
}
//This approach & code is contributed by Nikhil B.

Output
Sorted array is 
2 2 1 1 8 8 3 5 6 7 9 

Time complexity: O(M Log M + N Log M), M Log M for making self balancing bst of A1[] of size M.
Auxiliary Space: O(M), space for making a self-balancing BST for A1[] of size M.

Sort an array according to the order defined by another array using Hashing:

The idea is to use hashing. Store the frequency of A1[] and decrement the frequency in the A2[] order.

Follow the steps to solve the problem:

  • Loop through A1[], store the count of every number in a HashMap (key: number, value: count of number)
  • Loop through A2[], check if it is present in HashMap, if so, put in output array that many times and remove the number from HashMap.
  • Sort the rest of the numbers present in HashMap and put in the output array.

Below is the implementation of the above approach:

C++
// A C++ program to sort an array according to the order
// defined by another array
#include <bits/stdc++.h>
using namespace std;

// function to sort A1 according to A2 using hash map in C++
void sortA1ByA2(int A1[], int N, int A2[], int M, int ans[])
{
    map<int, int> mp;

    // indexing for answer = ans array
    int ind = 0;

    // initially storing frequency of each element of A1 in
    // map [ key, value ] = [ A1[i] , frequency[ A1[i] ] ]
    for (int i = 0; i < N; i++) {
        mp[A1[i]] += 1;
    }

    // traversing each element of A2, first come first serve
    for (int i = 0; i < M; i++) {

        // checking if current element of A2 is present in
        // A1 or not if not present go to next iteration
        // else store number of times it is appearing in A1
        // in ans array
        if (mp[A2[i]] != 0) {

            // mp[ A2[i] ] = frequency of A2[i] element in
            // A1 array
            for (int j = 1; j <= mp[A2[i]]; j++)
                ans[ind++] = A2[i];
        }

        // to avoid duplicate storing of same element of A2
        // in ans array
        mp.erase(A2[i]);
    }

    // store the remaining elements of A1 in sorted order in
    // ans array
    for (auto it : mp) {

        // it.second = frequency of remaining elements
        for (int j = 1; j <= it.second; j++)
            ans[ind++] = it.first;
    }
}

// Utility function to print an array
void printArray(int arr[], int n)
{
    // Iterate in the array
    for (int i = 0; i < n; i++)
        cout << arr[i] << " ";
    cout << endl;
}

// Driver Code
int main()
{
    int A1[] = { 2, 1, 2, 5, 7, 1, 9, 3, 6, 8, 8 };
    int A2[] = { 2, 1, 8, 3 };
    int n = sizeof(A1) / sizeof(A1[0]);
    int m = sizeof(A2) / sizeof(A2[0]);

    // The ans array is used to store the final sorted array
    int ans[n];
    sortA1ByA2(A1, n, A2, m, ans);

    // Prints the sorted array
    cout << "Sorted array is \n";
    printArray(ans, n);

    return 0;
}
Java
// A Java program to sort an array according to the order
// defined by another array

import java.io.*;
import java.util.Arrays;
import java.util.HashMap;

class GFG {
    // function to sort A1 according to A2 using hash map in
    // C++
    static void sortA1ByA2(int A1[], int N, int A2[], int M,
                           int ans[])
    {
        HashMap<Integer, Integer> mp = new HashMap<>();

        // indexing for answer = ans array
        int ind = 0;

        // initially storing frequency of each element of A1
        // in map [ key, value ] = [ A1[i] , frequency[
        // A1[i] ] ]
        for (int i = 0; i < N; i++) {
            if (!mp.containsKey(A1[i]))
                mp.put(A1[i], 1);
            else
                mp.put(A1[i], mp.get(A1[i]) + 1);
        }

        // traversing each element of A2, first come first
        // serve
        for (int i = 0; i < M; i++) {

            // checking if current element of A2 is present
            // in A1 or not if not present go to next
            // iteration else store number of times it is
            // appearing in A1 in ans array

            if (mp.containsKey(A2[i])) {

                // mp[ A2[i] ] = frequency of A2[i] element
                // in A1 array
                for (int j = 1; j <= mp.get(A2[i]); j++)
                    ans[ind++] = A2[i];
            }

            // to avoid duplicate storing of same element of
            // A2 in ans array
            mp.remove(A2[i]);
        }

        int idx = ind;
        // store the remaining elements of A1 in sorted
        // order in ans array
        for (HashMap.Entry<Integer, Integer> it :
             mp.entrySet()) {

            // it.second = frequency of remaining elements
            for (int j = 1; j <= it.getValue(); j++)
                ans[ind++] = it.getKey();
        }
        Arrays.sort(ans, idx, N);
    }

    // Utility function to print an array
    static void printArray(int arr[], int n)
    {
        for (int i = 0; i < n; i++)
            System.out.print(arr[i] + " ");
        System.out.println();
    }

    // Driver code
    public static void main(String[] args)
    {
        int A1[] = { 2, 1, 2, 5, 7, 1, 9, 3, 6, 8, 8 };
        int A2[] = { 2, 1, 8, 3 };
        int n = A1.length;
        int m = A2.length;

        // The ans array is used to store the final sorted
        // array
        int ans[] = new int[n];
        sortA1ByA2(A1, n, A2, m, ans);

        System.out.println("Sorted array is ");
        printArray(ans, n);
    }
}

// This code is contributed by Pushpesh Raj.
Python3
from collections import Counter

# Function to sort arr1
# according to arr2


def solve(arr1, arr2):
    # Our output array
    res = []

    # Counting Frequency of each
    # number in arr1
    f = Counter(arr1)

    # Iterate over arr2 and append all
    # occurrences of element of
    # arr2 from arr1
    for e in arr2:

        # Appending element 'e',
        # f[e] number of times
        res.extend([e]*f[e])

        # Count of 'e' after appending is zero
        f[e] = 0

    # Remaining numbers in arr1 in sorted
    # order (Numbers with non-zero frequency)
    rem = list(sorted(filter(
        lambda x: f[x] != 0, f.keys())))

    # Append them also
    for e in rem:
        res.extend([e]*f[e])

    return res


# Driver Code
if __name__ == "__main__":
    arr1 = [2, 1, 2, 5, 7, 1, 9, 3, 6, 8, 8]
    arr2 = [2, 1, 8, 3]
    print(*solve(arr1, arr2))
C#
// A C# program to sort an array according to the order
// defined by another array
using System;
using System.Collections.Generic;
class GFG 
{

  // Utility function to print an array
  static void printArray(int[] arr, int n)
  {
    
    // Iterate in the array
    for (int i = 0; i < n; i++)
      Console.Write(arr[i] + " ");
    Console.WriteLine();
  }

  // function to sort A1 according to A2 using hash map in
  // C++
  static void sortA1ByA2(int[] A1, int N, int[] A2, int M,
                         int[] ans)
  {

    Dictionary<int, int> mp
      = new Dictionary<int, int>();
    // indexing for answer = ans array
    int ind = 0;

    // initially storing frequency of each element of A1
    // in map [ key, value ] = [ A1[i] , frequency[
    // A1[i] ] ]
    for (int i = 0; i < N; i++) {
      if (mp.ContainsKey(A1[i])) {
        var val = mp[A1[i]];
        mp.Remove(A1[i]);
        mp.Add(A1[i], val + 1);
      }
      else
        mp.Add(A1[i], 1);
    }

    // traversing each element of A2, first come first
    // serve
    for (int i = 0; i < M; i++) {

      // checking if current element of A2 is present
      // in A1 or not if not present go to next
      // iteration else store number of times it is
      // appearing in A1 in ans array
      if (mp[A2[i]] != 0) {

        // mp[ A2[i] ] = frequency of A2[i] element
        // in A1 array
        for (int j = 1; j <= mp[A2[i]]; j++)
          ans[ind++] = A2[i];
      }

      // to avoid duplicate storing of same element of
      // A2 in ans array
      mp.Remove(A2[i]);
    }

    // store the remaining elements of A1 in sorted
    // order in ans array
    foreach(KeyValuePair<int, int> it in mp)
    {

      // it.second = frequency of remaining elements
      for (int j = 1; j <= it.Value; j++)
        ans[ind++] = it.Key;
    }
  }

  static void Main()
  {
    int[] A1 = { 2, 1, 2, 5, 7, 1, 9, 3, 6, 8, 8 };
    int[] A2 = { 2, 1, 8, 3 };
    int n = A1.Length;
    int m = A2.Length;

    // The ans array is used to store the final sorted
    // array
    int[] ans = new int[n];
    sortA1ByA2(A1, n, A2, m, ans);

    // Prints the sorted array
    Console.WriteLine("Sorted array is  ");
    printArray(ans, n);
  }
}

// This code is contributed by garg28harsh.
Javascript
<script>

// A JavaScript program to sort an array according to the order
// defined by another array

// function to sort A1 according to A2 using hash map in C++
function sortA1ByA2(A1, N, A2, M, ans)
{
    let mp = new Map();

    // indexing for answer = ans array
    let ind = 0;

    // initially storing frequency of each element of A1 in
    // map [ key, value ] = [ A1[i] , frequency[ A1[i] ] ]
    for (let i = 0; i < N; i++) {
        if(!mp.has(A1[i])){
            mp.set(A1[i],1);
        }
        else mp.set(A1[i],mp.get(A1[i]) + 1);
    }

    // traversing each element of A2, first come first serve
    for (let i = 0; i < M; i++) {

        // checking if current element of A2 is present in
        // A1 or not if not present go to next iteration
        // else store number of times it is appearing in A1
        // in ans array
        if (mp.has(A2[i])) {

            // mp[ A2[i] ] = frequency of A2[i] element in
            // A1 array
            for (let j = 1; j <= mp.get(A2[i]); j++)
                ans[ind++] = A2[i];
        }

        // to avoid duplicate storing of same element of A2
        // in ans array
        mp.delete(A2[i]);
    }

    // store the remaining elements of A1 in sorted order in
    // ans array

    mp = new Map([...mp.entries()].sort());

    for (let [key,value] of mp) {

        // it.second = frequency of remaining elements
        for (let j = 1; j <= value; j++)
            ans[ind++] = key;
    }
}

// Utility function to print an array
function printArray(arr, n)
{
    // Iterate in the array
    for (let i = 0; i <n; i++)
        document.write(arr[i]," ");
    document.write("</br>");
}

// Driver Code

let A1 = [ 2, 1, 2, 5, 7, 1, 9, 3, 6, 8, 8 ];
let A2 = [ 2, 1, 8, 3 ];
let n = A1.length;
let m = A2.length;

// The ans array is used to store the final sorted array
let ans = new Array(n);
sortA1ByA2(A1, n, A2, m, ans);

// Prints the sorted array
document.write("Sorted array is ");
printArray(ans, n);

// This code is contributed by shinjanpatra
</script>

Output
Sorted array is 
2 2 1 1 8 8 3 5 6 7 9 

Time Complexity: O(M + N + N log N); O(M+N) for traversing over both the array for hashing & retrieval. O(N log N) for sorting the remaining array of A1[].
Auxiliary Space: O(N), Space for storing frequency of A1[] of size N.

Sort an array according to the order defined by another array By Writing a Customized Comparator Method:

The idea is to make a customized comparator.

Follow the steps below to solve the problem:

  • If num1 and num2 both are in A2 then the number with a lower index in A2 will be treated smaller than others.
  • If only one of num1 or num2 present in A2, then that number will be treated smaller than the other which doesn’t present in A2.
  • If both are not in A2, then the natural ordering will be taken.

The time complexity of this method is O(mnLogm) if we use a O(nLogn) time complexity sorting algorithm. We can improve time complexity to O(mLogm) by using a Hashing instead of doing linear search.

Below is the implementation of the above approach: 

C++
// A C++ program to sort an array according to the order
// defined by another array

#include <bits/stdc++.h>
using namespace std;

// function that sorts the first array based on order of
// them in second array
void sortA1ByA2(vector<int>& arr1, vector<int>& arr2)
{

    // map to store the indices of second array
    // so that we can easily judge the position of two
    // elements in first array
    unordered_map<int, int> index;

    for (int i = 0; i < arr2.size(); i++) {
        // assigning i+1
        // because by default value of map is zero
        // Consider only first occurrence of element
        if (index[arr2[i]] == 0) {
            index[arr2[i]] = i + 1;
        }
    }

    // comparator function that sorts arr1 based on order
    // defined in arr2
    auto comp = [&](int a, int b) {
        // if indices of two elements are equal
        // we need to sort them in increasing order
        if (index[a] == 0 && index[b] == 0)
            return a < b;

        // if a not present in arr2 then b should come
        // before it
        if (index[a] == 0)
            return false;

        // if b not present in arr2 then no swap
        if (index[b] == 0)
            return true;

        // sorting in increasing order
        return index[a] < index[b];
    };

    sort(arr1.begin(), arr1.end(), comp);
}

int main()
{

    vector<int> arr1{ 2, 1, 2, 5, 7, 1, 9, 3, 6,
                      8, 8, 7, 5, 6, 9, 7, 5 };
    vector<int> arr2{ 2, 1, 8, 3, 4, 1 };

    sortA1ByA2(arr1, arr2);

    // printing the array
    cout << "Sorted array is  \n";
    for (auto i : arr1) {
        cout << i << " ";
    }

    return 0;
}
C
// A C++ program to sort an array according to the order
// defined by another array
#include <stdio.h>
#include <stdlib.h>

// A2 is made global here so that it can be accessed by
// compareByA2() The syntax of qsort() allows only two
// parameters to compareByA2()
int A2[5];

// size of A2[]
int size = 5;

int search(int key)
{
    int i = 0, idx = 0;
    for (i = 0; i < size; i++)
        if (A2[i] == key)
            return i;
    return -1;
}

// A custom compare method to compare elements of A1[]
// according to the order defined by A2[].
int compareByA2(const void* a, const void* b)
{
    int idx1 = search(*(int*)a);
    int idx2 = search(*(int*)b);
    if (idx1 != -1 && idx2 != -1)
        return idx1 - idx2;
    else if (idx1 != -1)
        return -1;
    else if (idx2 != -1)
        return 1;
    else
        return (*(int*)a - *(int*)b);
}

// This method mainly uses qsort to sort A1[] according to
// A2[]
void sortA1ByA2(int A1[], int size1)
{
    qsort(A1, size1, sizeof(int), compareByA2);
}

// Driver program to test above function
int main(int argc, char* argv[])
{
    int A1[] = { 2, 1, 2, 5, 7, 1, 9, 3, 6,
                 8, 8, 7, 5, 6, 9, 7, 5 };

    // A2[] = {2, 1, 8, 3, 4};
    A2[0] = 2;
    A2[1] = 1;
    A2[2] = 8;
    A2[3] = 3;
    A2[4] = 4;
    int size1 = sizeof(A1) / sizeof(A1[0]);

    sortA1ByA2(A1, size1);

    printf("Sorted Array is ");
    int i;
    for (i = 0; i < size1; i++)
        printf("%d ", A1[i]);
    return 0;
}
Java
// A Java program to sort an array according to the order
// defined by another array

import java.io.*;
import java.util.Arrays;
import java.util.HashMap;

class GFG {

    static void sortAccording(int[] A1, int[] A2, int m,
                              int n)
    {
        // HashMap to store the indices of elements in
        // the second array
        HashMap<Integer, Integer> index = new HashMap<>();

        for (int i = 0; i < n; i++) {
            // Consider only first occurrence of element
            if (!index.containsKey(A2[i]))
                // Assign value of i+1
                index.put(A2[i], i + 1);
        }

        // Since Java does not support custom comparators on
        // primitive data types, we box the elements in
        // wrapper classes.

        // Sorted values are stored in a temporary
        // array.
        int[] tmp
            = Arrays.stream(A1)
                  .boxed()
                  .sorted((p1, p2) -> {
                      int idx1 = index.getOrDefault(p1, 0);
                      int idx2 = index.getOrDefault(p2, 0);

                      // If both p1 and p2 are not present
                      // in the second array,
                      // sort them in ascending order
                      if (idx1 == 0 && idx2 == 0)
                          return p1 - p2;

                      // If only p2 is present in the second
                      // array, p2 comes before p1
                      if (idx1 == 0)
                          return 1;

                      // If only p1 is present in the second
                      // array, p1 comes before p2 (no swap)
                      if (idx2 == 0)
                          return -1;

                      // If both p1 and p2 are present in
                      // the second array, sort them
                      // according to their respective
                      // indices
                      return idx1 - idx2;
                  })
                  .mapToInt(i -> i)
                  .toArray();

        // Sorted values are copied to the original
        // array
        for (int i = 0; i < m; i++) {
            A1[i] = tmp[i];
        }
    }

    // Driver program to test the above function
    public static void main(String[] args)
    {
        int A1[] = { 2, 1, 2, 5, 7, 1, 9, 9, 3, 6, 8, 8 };
        int A2[] = { 2, 1, 8, 3, 1 };
        int m = A1.length;
        int n = A2.length;
        sortAccording(A1, A2, m, n);
        System.out.println("Sorted array is ");
        System.out.println(Arrays.toString(A1));
    }
}

// This code is contributed by anonymouscegian
Python3
# A python program to sort an array according to the order
# defined by another array
import functools

# function that sorts the first array based on order of
# them in second array
def sortA1ByA2(arr1, arr2):

    # map to store the indices of second array
    # so that we can easily judge the position of two
    # elements in first array
    index = {}

    for i in range(len(arr2)):
        # Consider only first occurrence of element
        if arr2[i] not in index.keys():
            # Assign value of i+1
            index[arr2[i]] = i + 1

    def cmp(a, b):
        
        # If both a and b are not present in the second array, 
        # sort them in ascending order
        if a not in index.keys() and b not in index.keys():
            return a-b
        
        # If only b is present in the second array, b comes before a
        if a not in index.keys():
            return 1
        
        # If only a is present in the second array, a comes before b
        if b not in index.keys():
            return -1
        
        # If both a and b are present in the second array,
        # sort them according to their respective indices
        return index[a]-index[b]
        
    arr1.sort(key=functools.cmp_to_key(cmp))


arr1 = [ 2, 1, 2, 5, 7, 1, 9, 3, 6, 8, 8, 7, 5, 6, 9, 7, 5 ]
arr2 = [ 2, 1, 8, 3, 4, 1 ]

sortA1ByA2(arr1, arr2)

# printing the array
print("Sorted array is ")
for i in range(len(arr1)):
    print(arr1[i], end = " ")
    
# The code is contributed by Nidhi goel. 
C#
using System;
using System.Collections.Generic;

class GFG
{
    // function that sorts the first array based on order of
    // them in second array
    static void sortA1ByA2(ref int[] arr1, int[] arr2)
    {
        // dictionary to store the indices of second array
        // so that we can easily judge the position of two
        // elements in first array
        Dictionary<int, int> index = new Dictionary<int, int>();

        for (int i = 0; i < arr2.Length; i++)
        {
            // assigning i+1
            // because by default value of dictionary is zero
            // Consider only first occurrence of element
            if (!index.ContainsKey(arr2[i]))
            {
                index[arr2[i]] = i + 1;
            }
        }

        // comparator function that sorts arr1 based on order
        // defined in arr2
        Array.Sort(arr1, (a, b) =>
        {
            // if indices of two elements are equal
            // we need to sort them in increasing order
            if (!index.ContainsKey(a) && !index.ContainsKey(b))
            {
                return a.CompareTo(b);
            }

            // if a not present in arr2 then b should come
            // before it
            if (!index.ContainsKey(a))
            {
                return 1;
            }

            // if b not present in arr2 then no swap
            if (!index.ContainsKey(b))
            {
                return -1;
            }

            // sorting in increasing order
            return index[a].CompareTo(index[b]);
        });
    }

    static void Main(string[] args)
    {
        int[] arr1 = new int[] { 2, 1, 2, 5, 7, 1, 9, 3, 6, 8, 8, 7, 5, 6, 9, 7, 5 };
        int[] arr2 = new int[] { 2, 1, 8, 3, 4, 1 };

        sortA1ByA2(ref arr1, arr2);

        // printing the array
        Console.WriteLine("Sorted array is");
        foreach (int i in arr1)
        {
            Console.Write(i + " ");
        }
        Console.WriteLine();
    }
}
// This code is contributed by Shivam Tiwari
Javascript
function sortAccording(A1, A2) {
    // Map to store the indices of elements in the second array
    let index = new Map();

    for (let i = 0; i < A2.length; i++) {
        // Consider only first occurrence of element
        if (!index.has(A2[i])) {
            // Assign value of i+1
            index.set(A2[i], i + 1);
        }
    }

    A1.sort((a, b) => {
        let idx1 = index.get(a) || 0;
        let idx2 = index.get(b) || 0;

        // If both a and b are not present in the second array, sort them in ascending order
        if (idx1 === 0 && idx2 === 0) {
            return a - b;
        }

        // If only b is present in the second array, b comes before a
        if (idx1 === 0) {
            return 1;
        }

        // If only a is present in the second array, a comes before b
        if (idx2 === 0) {
            return -1;
        }

        // If both a and b are present in the second array, sort them according to their respective indices
        return idx1 - idx2;
    });
}

// Driver Code
let A1 = [2, 1, 2, 5, 7, 1, 9, 9, 3, 6, 8, 8];
let A2 = [2, 1, 8, 3, 1];
sortAccording(A1, A2);
console.log("Sorted array is ");
console.log(A1);
// This code is contributed by Shivam Tiwari

Output
Sorted array is  
2 2 1 1 8 8 3 5 5 5 6 6 7 7 7 9 9 

Time complexity: O(MLogM + N), MLogM for sorting Arr1[] of size M and N for iterating over Arr2[] of size N.
Auxiliary Space: O(N),  Storing first occurrence of every element of arr2[] of size N.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads