Open In App

Sorting an array according to another array using pair in STL

Improve
Improve
Like Article
Like
Save
Share
Report

We are given two arrays. We need to sort one array according to another. Examples:

Input : 2 1 5 4 9 3 6 7 10 8
A B C D E F G H I J
Output : 1 2 3 4 5 6 7 8 9 10
B A F D C G H J E I
Here we are sorting second array
(a character array) according to
the first array (an integer array).

We have discussed different ways in below post. Sort an array according to the order defined by another array In this post we are focusing on using the pair container present in STL of C++. To achieve our task we are going to make pairs of respective elements from both the arrays.Then simply use the sort function. The important thing to note is, the first element in the pairs should be from the array according to which the sorting is to be performed. 

Here are the steps to solve this problem :

  1. Construct a pair array pairt[] of type pair<int, char> having size n (here n is the size of the input arrays)
  2. Fill the pair array with the respective elements from the input arrays a[] and b[].
  3. Using the sort() method from the STL sort the pair array pairt[]. Sorting will be based on the array of integers a[] which is the first element in the pair.
  4. Use the components in the sorted pair array pairt[] to modify the initial input arrays a[] and b[].
  5. At last, print the sorted arrays a[] and b[].

CPP




// Sort an array according to
// other using pair in STL.
#include <bits/stdc++.h>
using namespace std;
 
// Function to sort character array b[]
// according to the order defined by a[]
void pairsort(int a[], char b[], int n)
{
    pair<int, char> pairt[n];
 
    // Storing the respective array
    // elements in pairs.
    for (int i = 0; i < n; i++)
    {
        pairt[i].first = a[i];
        pairt[i].second = b[i];
    }
 
    // Sorting the pair array.
    sort(pairt, pairt + n);
     
    // Modifying original arrays
    for (int i = 0; i < n; i++)
    {
        a[i] = pairt[i].first;
        b[i] = pairt[i].second;
    }
}
 
// Driver function
int main()
{
    int a[] = {2, 1, 5, 4, 9, 3, 6, 7, 10, 8};
    char b[] = {'A', 'B', 'C', 'D', 'E', 'F',
                         'G', 'H', 'I', 'J'};
                          
    int n = sizeof(a) / sizeof(a[0]);
     
    // Function calling
    pairsort(a, b, n);
 
    for (int i = 0; i < n; i++)
        cout << a[i] << " ";
    cout << endl;
 
    for (int i = 0; i < n; i++)
        cout << b[i] << " ";
         
    return 0;
}


Java




// Nikunj Sonigara
 
import java.util.Arrays;
 
public class Main {
 
    // Function to sort integer array b[]
    // according to the order defined by a[]
    static void pairSort(int[] a, char[] b, int n) {
        // Creating an array of pairs
        Pair[] pairArr = new Pair[n];
 
        // Storing the respective array
        // elements in pairs.
        for (int i = 0; i < n; i++) {
            pairArr[i] = new Pair(a[i], b[i]);
        }
 
        // Sorting the pair array.
        Arrays.sort(pairArr);
 
        // Modifying original arrays
        for (int i = 0; i < n; i++) {
            a[i] = pairArr[i].first;
            b[i] = pairArr[i].second;
        }
    }
 
    // Driver function
    public static void main(String[] args) {
        int[] a = {2, 1, 5, 4, 9, 3, 6, 7, 10, 8};
        char[] b = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'};
        int n = a.length;
 
        // Function calling
        pairSort(a, b, n);
 
        // Printing the sorted arrays
        for (int i = 0; i < n; i++) {
            System.out.print(a[i] + " ");
        }
        System.out.println();
 
        for (int i = 0; i < n; i++) {
            System.out.print(b[i] + " ");
        }
    }
 
    // Class representing a pair
    static class Pair implements Comparable<Pair> {
        int first;
        char second;
 
        public Pair(int first, char second) {
            this.first = first;
            this.second = second;
        }
 
        // Comparing pairs based on their first element
        @Override
        public int compareTo(Pair pair) {
            return Integer.compare(this.first, pair.first);
        }
    }
}


Python3




# Function to sort character array b[]
# according to the order defined by a[]
def pairsort(a, b, n):
    pairt = [(a[i], b[i]) for i in range(n)]
 
    # Sorting the pair array.
    pairt.sort()
 
    # Modifying original arrays
    for i in range(n):
        a[i] = pairt[i][0]
        b[i] = pairt[i][1]
 
# Driver function
if __name__ == "__main__":
    a = [2, 1, 5, 4, 9, 3, 6, 7, 10, 8]
    b = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J']
    n = len(a)
     
    # Function calling
    pairsort(a, b, n)
 
    for i in range(n):
        print(a[i], end=" ")
    print()
 
    for i in range(n):
        print(b[i], end=" ")


C#




using System;
 
class MainClass
{
    // Function to sort array b[]
    // according to the order defined by a[]
    static void pairsort(int[] a, char[] b, int n)
    {
        Tuple<int, char>[] pairt = new Tuple<int, char>[n];
 
        // Storing the respective array
        // elements in pairs.
        for (int i = 0; i < n; i++)
        {
            pairt[i] = Tuple.Create(a[i], b[i]);
        }
 
        // Sorting the array of pairs.
        Array.Sort(pairt);
 
        // Modifying original arrays
        for (int i = 0; i < n; i++)
        {
            a[i] = pairt[i].Item1;
            b[i] = pairt[i].Item2;
        }
    }
 
    // Driver function
    public static void Main(string[] args)
    {
        int[] a = { 2, 1, 5, 4, 9, 3, 6, 7, 10, 8 };
        char[] b = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J' };
        int n = a.Length;
 
        // Function calling
        pairsort(a, b, n);
 
        // Displaying the sorted array a[]
        foreach (int num in a)
        {
            Console.Write(num + " ");
        }
        Console.WriteLine();
 
        // Displaying the corresponding sorted array b[]
        foreach (char ch in b)
        {
            Console.Write(ch + " ");
        }
    }
}


Javascript




// Function to sort arrays b[] according to the order defined by a[]
function pairsort(a, b, n) {
    let pairt = [];
 
    // Storing the respective array elements in pairs.
    for (let i = 0; i < n; i++) {
        pairt.push({ first: a[i], second: b[i] });
    }
 
    // Sorting the pair array.
    pairt.sort((x, y) => x.first - y.first);
 
    // Modifying original arrays
    for (let i = 0; i < n; i++) {
        a[i] = pairt[i].first;
        b[i] = pairt[i].second;
    }
}
 
// Driver function
function main() {
    let a = [2, 1, 5, 4, 9, 3, 6, 7, 10, 8];
    let b = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'];
    let n = a.length;
 
    // Function calling
    pairsort(a, b, n);
 
    // Display sorted arrays
    console.log(a.join(' '));
    console.log(b.join(' '));
}
 
// Calling the main function
main();


Output:

1 2 3 4 5 6 7 8 9 10 
B A F D C G H J E I

Complexity Analysis :

  • Time complexity : O(nlogn)  overall time complexity of the program is dominated by the sort() function
  • Space complexity : O(n) because the program creates a pair array pairt[] of size n to store the elements from the input arrays.

If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.



Last Updated : 09 Jan, 2024
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads