GeeksforGeeks App
Open App
Browser
Continue

# Sorting Vector of Pairs by 1st element in ascending and 2nd element in descending

A pair is a container that stores two values mapped to each other, and a vector containing multiple numbers of such pairs is called a vector of pairs.

While solving problems there come many instances where there is a need to sort the elements of vector on the basis of both the first and second elements of the pair. In that instance we have to pass an additional argument to the sort() function i, e a call to a user-defined explicit function in the sort() function.
This article focuses on discussing the sorting vector of pairs on the basis of the first element of pairs in ascending order and if the first element if equal then according to the second element in descending order.

Below is the C++ program to demonstrate the sorting of vectors of pairs.

## C++

 `// C++ program to implement``// the above approach``#include ``using` `namespace` `std;` `// Function to sort the vector elements``// ascending for first element``// and if first element equal``// then descending for second element``bool` `sortbyCond(``const` `pair<``int``, ``int``>& a,``                ``const` `pair<``int``, ``int``>& b)``{``    ``if` `(a.first != b.first)``        ``return` `(a.first < b.first);``    ``else``       ``return` `(a.second > b.second);``}` `// Driver code``int` `main()``{``    ``// Declaring vector of pairs``    ``vector > vect;` `    ``// Initialising 1st and 2nd element``    ``// of pairs with array values``    ``int` `arr[] = { 10, 10, 5, 5, 15, 15 };``    ``int` `arr1[] = { 40, 60, 20, 50, 12, 24 };``    ``int` `n = ``sizeof``(arr) / ``sizeof``(arr[0]);` `    ``// Entering values in vector of pairs``    ``for` `(``int` `i = 0; i < n; i++)``        ``vect.push_back(make_pair(arr[i],``                                 ``arr1[i]));` `    ``// The original vector(before sort())``    ``cout << ``"The vector before sort operation is:\n"``;``    ``for` `(``int` `i = 0; i < n; i++) {``        ``// "first" and "second" are used to``        ``// access 1st and 2nd element of pair``        ``// respectively``        ``cout << vect[i].first << ``" "``             ``<< vect[i].second << endl;``    ``}` `    ``// Using sort() function to sort by``    ``// 1st element of pair and if first``    ``// element equal then by descending``    ``// order of second element``    ``sort(vect.begin(), vect.end(), sortbyCond);` `    ``// Printing the sorted vector(after``    ``// using sort())``    ``cout << ``"The vector after sort operation is:\n"``;``    ``for` `(``int` `i = 0; i < n; i++) {``        ``// "first" and "second" are used to``        ``// access 1st and 2nd element of pair``        ``// respectively``        ``cout << vect[i].first << ``" "``             ``<< vect[i].second << endl;``    ``}``    ``return` `0;``}`

## Java

 `import` `java.util.*;` `public` `class` `Main {``    ``public` `static` `void` `main(String[] args)``    ``{``        ``// Create a list to store the vector``        ``List<``int``[]> vect = ``new` `ArrayList<>();` `        ``// Initialize the arrays``        ``int``[] arr = { ``10``, ``10``, ``5``, ``5``, ``15``, ``15` `};``        ``int``[] arr1 = { ``40``, ``60``, ``20``, ``50``, ``12``, ``24` `};` `        ``// Get the length of the arrays``        ``int` `n = arr.length;` `        ``// Create a 2D array to represent the vector and add``        ``// each pair to the list``        ``for` `(``int` `i = ``0``; i < n; i++) {``            ``int``[] temp = { arr[i], arr1[i] };``            ``vect.add(temp);``        ``}` `        ``// Print the vector before the sort operation``        ``System.out.println(``            ``"The vector before sort operation is: "``);``        ``for` `(``int` `i = ``0``; i < n; i++) {``            ``System.out.println(vect.get(i)[``0``] + ``" "``                               ``+ vect.get(i)[``1``]);``        ``}` `        ``// Sort the vector using a custom comparator``        ``Collections.sort(vect, ``new` `Comparator<``int``[]>() {``            ``public` `int` `compare(``int``[] a, ``int``[] b)``            ``{``                ``// If the first elements are not equal, sort``                ``// based on the first element``                ``if` `(a[``0``] != b[``0``]) {``                    ``return` `a[``0``] - b[``0``];``                ``}``                ``// If the first elements are equal, sort``                ``// based on the second element in descending``                ``// order``                ``else` `{``                    ``return` `b[``1``] - a[``1``];``                ``}``            ``}``        ``});` `        ``// Print the vector after the sort operation``        ``System.out.println(``            ``"The vector after sort operation is: "``);``        ``for` `(``int` `i = ``0``; i < n; i++) {``            ``System.out.println(vect.get(i)[``0``] + ``" "``                               ``+ vect.get(i)[``1``]);``        ``}``    ``}``}`

## Python3

 `# Python program to implement``# the above approach` `# Function to sort the vector elements``# ascending for first element``# and if first element equal``# then descending for second element``from` `functools ``import` `cmp_to_key` `def` `sortbyCond(a, b):``    ``if` `(a[``0``] !``=` `b[``0``]):``        ``return` `(a[``0``] ``-` `b[``0``])``    ``else``:``        ``return` `b[``1``] ``-` `a[``1``]` `# Driver code` `# Declaring vector of pairs``vect ``=` `[]` `# Initialising 1st and 2nd element``# of pairs with array values``arr ``=` `[ ``10``, ``10``, ``5``, ``5``, ``15``, ``15` `]``arr1 ``=` `[ ``40``, ``60``, ``20``, ``50``, ``12``, ``24` `]``n ``=` `len``(arr)` `# Entering values in vector of pairs``for` `i ``in` `range``(n):``    ``vect.append([arr[i],arr1[i]])` `# The original vector(before sort())``print``(``"The vector before sort operation is: "``)``for` `i ``in` `range``(n):` `    ``# "first" and "second" are used to``    ``# access 1st and 2nd element of pair``    ``# respectively``    ``print``(f``"{vect[i][0]} {vect[i][1]}"``)`  `# Using sort() function to sort by``# 1st element of pair and if first``# element equal then by descending``# order of second element``vect.sort(key ``=` `cmp_to_key(sortbyCond))` `# Printing the sorted vector(after``# using sort())``print``(``"The vector after sort operation is: "``)``for` `i ``in` `range``(n):` `    ``# "first" and "second" are used to``    ``# access 1st and 2nd element of pair``    ``# respectively``    ``print``(f``"{vect[i][0]} {vect[i][1]}"``)` `# This code is contributed by shinjanpatra`

## C#

 `// C# program to implement``// the above approach``using` `System;``using` `System.Collections.Generic;` `public` `class` `GFG{` `    ``class` `pair : IComparable``    ``{``        ``public` `int` `first, second;``        ``public` `pair(``int` `first, ``int` `second)``        ``{``            ``this``.first = first;``            ``this``.second = second;``        ``}``         ``public` `int` `CompareTo(pair b)``         ``{``             ``if` `(``this``.first != b.first)``                ``return` `(``this``.first < b.first)?-1:1;``              ``else``                ``return` `this``.second > b.second?-1:1;``         ``}``    ``}`` ` `  ``// Driver code``  ``public` `static` `void` `Main(String[] args)``  ``{``    ` `    ``// Declaring vector of pairs``    ``List vect = ``new` `List ();` `    ``// Initialising 1st and 2nd element``    ``// of pairs with array values``    ``int` `[]arr = { 10, 10, 5, 5, 15, 15 };``    ``int` `[]arr1 = { 40, 60, 20, 50, 12, 24 };``    ``int` `n = arr.Length;` `    ``// Entering values in vector of pairs``    ``for` `(``int` `i = 0; i < n; i++)``      ``vect.Add(``new` `pair(arr[i],``                        ``arr1[i]));` `    ``// The original vector(before sort())``    ``Console.Write(``"The vector before sort operation is:\n"``);``    ``for` `(``int` `i = 0; i < n; i++)``    ``{``      ` `      ``// "first" and "second" are used to``      ``// access 1st and 2nd element of pair``      ``// respectively``      ``Console.Write(vect[i].first+ ``" "``                       ``+ vect[i].second +``"\n"``);``    ``}` `    ``// Using sort() function to sort by``    ``// 1st element of pair and if first``    ``// element equal then by descending``    ``// order of second element``    ``vect.Sort();` `    ``// Printing the sorted vector(after``    ``// using sort())``    ``Console.Write(``"The vector after sort operation is:\n"``);``    ``for` `(``int` `i = 0; i < n; i++)``    ``{``      ` `      ``// "first" and "second" are used to``      ``// access 1st and 2nd element of pair``      ``// respectively``      ``Console.Write(vect[i].first+ ``" "``                       ``+ vect[i].second +``"\n"``);``    ``}``  ``}``}` `// This code is contributed by shikhasingrajput`

## Javascript

 ``

Output

```The vector before sort operation is:
10 40
10 60
5 20
5 50
15 12
15 24
The vector after sort operation is:
5 50
5 20
10 60
10 40
15 24
15 12```

Time complexity:- O(n log n)

The space complexity is O(n), where n is the length of the input arrays. This is because the program creates a list of size n to store the vector. Additionally, the program creates a temporary array of size 2 for each element in the input arrays, which also contributes to the space complexity. The space complexity could be reduced by modifying the program to sort the input arrays in place instead of creating a separate list to store the vector.

My Personal Notes arrow_drop_up