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}
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++
#include <bits/stdc++.h>
using namespace std;
int first( int arr[], int low, int high, int x, int n)
{
if (high >= low) {
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;
}
void sortAccording( int A1[], int A2[], int m, int n)
{
int temp[m], visited[m];
for ( int i = 0; i < m; i++) {
temp[i] = A1[i];
visited[i] = 0;
}
sort(temp, temp + m);
int ind = 0;
for ( int i = 0; i < n; i++) {
int f = first(temp, 0, m - 1, A2[i], m);
if (f == -1)
continue ;
for ( int j = f; (j < m && temp[j] == A2[i]); j++) {
A1[ind++] = temp[j];
visited[j] = 1;
}
}
for ( int i = 0; i < m; i++)
if (visited[i] == 0)
A1[ind++] = temp[i];
}
void printArray( int arr[], int n)
{
for ( int i = 0; i < n; i++)
cout << arr[i] << " " ;
cout << endl;
}
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]);
cout << "Sorted array is \n" ;
sortAccording(A1, A2, m, n);
printArray(A1, m);
return 0;
}
|
Java
import java.io.*;
import java.util.Arrays;
class GFG {
static int first( int arr[], int low, int high, int x,
int n)
{
if (high >= low) {
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 ;
}
static void sortAccording( int A1[], int A2[], int m,
int n)
{
int temp[] = new int [m], visited[] = new int [m];
for ( int i = 0 ; i < m; i++) {
temp[i] = A1[i];
visited[i] = 0 ;
}
Arrays.sort(temp);
int ind = 0 ;
for ( int i = 0 ; i < n; i++) {
int f = first(temp, 0 , m - 1 , A2[i], m);
if (f == - 1 )
continue ;
for ( int j = f; (j < m && temp[j] == A2[i]);
j++) {
A1[ind++] = temp[j];
visited[j] = 1 ;
}
}
for ( int i = 0 ; i < m; i++)
if (visited[i] == 0 )
A1[ind++] = temp[i];
}
static void printArray( int arr[], int n)
{
for ( int i = 0 ; i < n; i++)
System.out.print(arr[i] + " " );
System.out.println();
}
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);
}
}
|
Python3
def first(arr, low, high, x, n):
if (high > = low):
mid = low + (high - low) / / 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
def sortAccording(A1, A2, m, n):
temp = [ 0 ] * m
visited = [ 0 ] * m
for i in range ( 0 , m):
temp[i] = A1[i]
visited[i] = 0
temp.sort()
ind = 0
for i in range ( 0 , n):
f = first(temp, 0 , m - 1 , A2[i], m)
if (f = = - 1 ):
continue
j = f
while (j < m and temp[j] = = A2[i]):
A1[ind] = temp[j]
ind = ind + 1
visited[j] = 1
j = j + 1
for i in range ( 0 , m):
if (visited[i] = = 0 ):
A1[ind] = temp[i]
ind = ind + 1
def printArray(arr, n):
for i in range ( 0 , n):
print (arr[i], end = " " )
print ("")
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)
|
C#
using System;
class GFG {
static int first( int [] arr, int low, int high, int x,
int n)
{
if (high >= low) {
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;
}
static void sortAccording( int [] A1, int [] A2, int m,
int n)
{
int [] temp = new int [m];
int [] visited = new int [m];
for ( int i = 0; i < m; i++) {
temp[i] = A1[i];
visited[i] = 0;
}
Array.Sort(temp);
int ind = 0;
for ( int i = 0; i < n; i++) {
int f = first(temp, 0, m - 1, A2[i], m);
if (f == -1)
continue ;
for ( int j = f; (j < m && temp[j] == A2[i]);
j++) {
A1[ind++] = temp[j];
visited[j] = 1;
}
}
for ( int i = 0; i < m; i++)
if (visited[i] == 0)
A1[ind++] = temp[i];
}
static void printArray( int [] arr, int n)
{
for ( int i = 0; i < n; i++)
Console.Write(arr[i] + " " );
Console.WriteLine();
}
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);
}
}
|
Javascript
<script>
function first(arr,low,high,x,n)
{
if (high >= low) {
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;
}
function sortAccording(A1,A2,m,n)
{
let temp=[];
let visited=[];
for (let i = 0; i < m; i++)
{
temp[i] = A1[i];
visited[i] = 0;
}
temp.sort( function (a, b){ return a-b});
let ind = 0;
for (let i = 0; i < n; i++)
{
let f = first(temp, 0, m - 1, A2[i], m);
if (f == -1)
{
continue ;
}
for (let j = f; (j < m && temp[j] == A2[i]);j++)
{
A1[ind++] = temp[j];
visited[j] = 1;
}
}
for (let i = 0; i < m; i++)
{
if (visited[i] == 0)
A1[ind++] = temp[i];
}
}
function printArray(arr,n)
{
for (let i = 0; i < n; i++)
{
document.write(arr[i] + " " );
}
document.write( "<br>" );
}
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);
</script>
|
PHP
<?php
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;
}
function sortAccording(& $A1 , & $A2 , $m , $n )
{
$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( $temp );
$ind = 0;
for ( $i = 0; $i < $n ; $i ++)
{
$f = first( $temp , 0, $m - 1, $A2 [ $i ], $m );
if ( $f == -1) continue ;
for ( $j = $f ; ( $j < $m &&
$temp [ $j ] == $A2 [ $i ]); $j ++)
{
$A1 [ $ind ++] = $temp [ $j ];
$visited [ $j ] = 1;
}
}
for ( $i = 0; $i < $m ; $i ++)
if ( $visited [ $i ] == 0)
$A1 [ $ind ++] = $temp [ $i ];
}
function printArray(& $arr , $n )
{
for ( $i = 0; $i < $n ; $i ++)
echo $arr [ $i ] . " " ;
echo "\n" ;
}
$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 );
?>
|
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[].
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[]
- 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[].
Time complexity: O(M Log M + N Log M), M Log M for making self balancing bst of arr1[] of size M.
Auxiliary Space: O(M), space for making self balancing bst for Arr1[] 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++
#include <bits/stdc++.h>
using namespace std;
void sortA1ByA2( int A1[], int N, int A2[], int M, int ans[])
{
map< int , int > mp;
int ind = 0;
for ( int i = 0; i < N; i++) {
mp[A1[i]] += 1;
}
for ( int i = 0; i < M; i++) {
if (mp[A2[i]] != 0) {
for ( int j = 1; j <= mp[A2[i]]; j++)
ans[ind++] = A2[i];
}
mp.erase(A2[i]);
}
for ( auto it : mp) {
for ( int j = 1; j <= it.second; j++)
ans[ind++] = it.first;
}
}
void printArray( int arr[], int n)
{
for ( int i = 0; i < n; i++)
cout << arr[i] << " " ;
cout << endl;
}
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]);
int ans[n];
sortA1ByA2(A1, n, A2, m, ans);
cout << "Sorted array is \n" ;
printArray(ans, n);
return 0;
}
|
Java
import java.io.*;
import java.util.Arrays;
import java.util.HashMap;
class GFG {
static void sortA1ByA2( int A1[], int N, int A2[], int M,
int ans[])
{
HashMap<Integer, Integer> mp = new HashMap<>();
int ind = 0 ;
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 );
}
for ( int i = 0 ; i < M; i++) {
if (mp.containsKey(A2[i])) {
for ( int j = 1 ; j <= mp.get(A2[i]); j++)
ans[ind++] = A2[i];
}
mp.remove(A2[i]);
}
int idx = ind;
for (HashMap.Entry<Integer, Integer> it :
mp.entrySet()) {
for ( int j = 1 ; j <= it.getValue(); j++)
ans[ind++] = it.getKey();
}
Arrays.sort(ans, idx, N);
}
static void printArray( int arr[], int n)
{
for ( int i = 0 ; i < n; i++)
System.out.print(arr[i] + " " );
System.out.println();
}
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;
int ans[] = new int [n];
sortA1ByA2(A1, n, A2, m, ans);
System.out.println( "Sorted array is " );
printArray(ans, n);
}
}
|
Python3
from collections import Counter
def solve(arr1, arr2):
res = []
f = Counter(arr1)
for e in arr2:
res.extend([e] * f[e])
f[e] = 0
rem = list ( sorted ( filter (
lambda x: f[x] ! = 0 , f.keys())))
for e in rem:
res.extend([e] * f[e])
return res
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#
using System;
using System.Collections.Generic;
class GFG
{
static void printArray( int [] arr, int n)
{
for ( int i = 0; i < n; i++)
Console.Write(arr[i] + " " );
Console.WriteLine();
}
static void sortA1ByA2( int [] A1, int N, int [] A2, int M,
int [] ans)
{
Dictionary< int , int > mp
= new Dictionary< int , int >();
int ind = 0;
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);
}
for ( int i = 0; i < M; i++) {
if (mp[A2[i]] != 0) {
for ( int j = 1; j <= mp[A2[i]]; j++)
ans[ind++] = A2[i];
}
mp.Remove(A2[i]);
}
foreach (KeyValuePair< int , int > it in mp)
{
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;
int [] ans = new int [n];
sortA1ByA2(A1, n, A2, m, ans);
Console.WriteLine( "Sorted array is " );
printArray(ans, n);
}
}
|
Javascript
<script>
function sortA1ByA2(A1, N, A2, M, ans)
{
let mp = new Map();
let ind = 0;
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);
}
for (let i = 0; i < M; i++) {
if (mp.has(A2[i])) {
for (let j = 1; j <= mp.get(A2[i]); j++)
ans[ind++] = A2[i];
}
mp. delete (A2[i]);
}
mp = new Map([...mp.entries()].sort());
for (let [key,value] of mp) {
for (let j = 1; j <= value; j++)
ans[ind++] = key;
}
}
function printArray(arr, n)
{
for (let i = 0; i <n; i++)
document.write(arr[i], " " );
document.write( "</br>" );
}
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;
let ans = new Array(n);
sortA1ByA2(A1, n, A2, m, ans);
document.write( "Sorted array is " );
printArray(ans, n);
</script>
|
Output
Sorted array is
2 2 1 1 8 8 3 5 6 7 9
Time Complexity: O(M + N), Traversing over both the array
Auxiliary Space: O(M), Space for storing frequency of arr1[] of size M.
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++
#include <bits/stdc++.h>
using namespace std;
void sortA1ByA2(vector< int >& arr1, vector< int >& arr2)
{
unordered_map< int , int > index;
for ( int i = 0; i < arr2.size(); i++) {
if (index[arr2[i]] == 0) {
index[arr2[i]] = i + 1;
}
}
auto comp = [&]( int a, int b) {
if (index[a] == 0 && index[b] == 0)
return a < b;
if (index[a] == 0)
return false ;
if (index[b] == 0)
return true ;
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);
cout << "Sorted array is \n" ;
for ( auto i : arr1) {
cout << i << " " ;
}
return 0;
}
|
C
#include <stdio.h>
#include <stdlib.h>
int A2[5];
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;
}
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);
}
void sortA1ByA2( int A1[], int size1)
{
qsort (A1, size1, sizeof ( int ), compareByA2);
}
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[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
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<Integer, Integer> index = new HashMap<>();
for ( int i = 0 ; i < n; i++) {
if (!index.containsKey(A2[i]))
index.put(A2[i], i + 1 );
}
int [] tmp
= Arrays.stream(A1)
.boxed()
.sorted((p1, p2) -> {
int idx1 = index.getOrDefault(p1, 0 );
int idx2 = index.getOrDefault(p2, 0 );
if (idx1 == 0 && idx2 == 0 )
return p1 - p2;
if (idx1 == 0 )
return 1 ;
if (idx2 == 0 )
return - 1 ;
return idx1 - idx2;
})
.mapToInt(i -> i)
.toArray();
for ( int i = 0 ; i < m; i++) {
A1[i] = tmp[i];
}
}
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));
}
}
|
Python3
import functools
def sortA1ByA2(arr1, arr2):
index = {}
for i in range ( len (arr2)):
if arr2[i] not in index.keys():
index[arr2[i]] = i + 1
def cmp (a, b):
if a not in index.keys() and b not in index.keys():
return a - b
if a not in index.keys():
return 1
if b not in index.keys():
return - 1
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)
print ( "Sorted array is " )
for i in range ( len (arr1)):
print (arr1[i], end = " " )
|
C#
using System;
using System.Collections.Generic;
class GFG
{
static void sortA1ByA2( ref int [] arr1, int [] arr2)
{
Dictionary< int , int > index = new Dictionary< int , int >();
for ( int i = 0; i < arr2.Length; i++)
{
if (!index.ContainsKey(arr2[i]))
{
index[arr2[i]] = i + 1;
}
}
Array.Sort(arr1, (a, b) =>
{
if (!index.ContainsKey(a) && !index.ContainsKey(b))
{
return a.CompareTo(b);
}
if (!index.ContainsKey(a))
{
return 1;
}
if (!index.ContainsKey(b))
{
return -1;
}
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);
Console.WriteLine( "Sorted array is" );
foreach ( int i in arr1)
{
Console.Write(i + " " );
}
Console.WriteLine();
}
}
|
Javascript
function sortAccording(A1, A2) {
let index = new Map();
for (let i = 0; i < A2.length; i++) {
if (!index.has(A2[i])) {
index.set(A2[i], i + 1);
}
}
A1.sort((a, b) => {
let idx1 = index.get(a) || 0;
let idx2 = index.get(b) || 0;
if (idx1 === 0 && idx2 === 0) {
return a - b;
}
if (idx1 === 0) {
return 1;
}
if (idx2 === 0) {
return -1;
}
return idx1 - idx2;
});
}
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);
|
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.
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
09 Aug, 2023
Like Article
Save Article