Dadas dos arrays A1[] y A2[], ordene A1 de tal manera que el orden relativo entre los elementos sea el mismo que el de A2. Para los elementos que no están presentes en A2, agréguelos al final en orden ordenado.
Ejemplo:
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.
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 ?>
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>
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]); } // 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(); } } // 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))
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>
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 accesed 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
Publicación traducida automáticamente
Artículo escrito por GeeksforGeeks-1 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA