Problems on Comparator Sort
Here are some problems that will help you better understand comparator sorting and its practical use cases.
Sort Strings by Length
Problem Description: Sort an array of strings based on their lengths, with shorter strings coming first. If two strings have the same length, maintain their relative order.
Intuition: We need to sort the strings based on their lengths. To achieve this, we can define a comparison logic in our comparator that compares the lengths of the strings and returns the shorter one.
Approach to solve the Problem:
- Create a collection of strings (e.g., a vector of strings).
- Define a comparator (either a function or lambda) that compares two strings by their length.
- Sort the collection using sort() and pass the comparator to it.
- Output the sorted strings after sorting.
Code Implementation
1. C++ Try on Compiler
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
// Comparator function to sort strings by length
bool compare(string a, string b) {
return a.size() < b.size(); // Compare by size
}
int main() {
// Array of strings to be sorted
vector<string> arr = {"apple", "banana", "kiwi", "grape"};
// Sort the array using the custom comparator
sort(arr.begin(), arr.end(), compare);
// Print sorted strings
for (const string& s : arr) {
cout << s << " ";
}
cout << endl;
}
2. Java Try on Compiler
import java.util.*;
public class Main {
public static void main(String[] args) {
// Array of strings to be sorted
String[] arr = {"apple", "banana", "kiwi", "grape"};
// Sort the array by length of strings
Arrays.sort(arr, (a, b) -> Integer.compare(a.length(), b.length()));
// Print sorted strings
System.out.println(Arrays.toString(arr));
}
}
3. Python Try on Compiler
# List of strings to be sorted
arr = ["apple", "banana", "kiwi", "grape"]
# Sort the list based on length of each string
arr.sort(key=len)
# Print sorted strings
print(arr)
4. Javascript Try on Compiler
// Array of strings to be sorted
const arr = ["apple", "banana", "kiwi", "grape"];
// Sort the array by length of strings
arr.sort((a, b) => a.length - b.length);
// Print sorted strings
console.log(arr);
Sort People by Name and Age
Problem Description: Sort a list of people alphabetically by name. If names are identical, sort them by age in descending order.
Intuition: Since we have the name and age of people as input, we can create a structure or class to store these values. We can then sort the list using a custom comparator with the following comparison logic:
- If the names of two people are different, we return the person with the lexicographically smaller (alphabetically first) name.
- If the names are the same, we return the person with the greater age.
Approach to solve the Problem:
- Define a Person structure with name and age fields.
- Create a comparator functor (a struct) that overrides the operator() to
- Compare by name alphabetically (ascending).
- If names are identical, compare by age in descending order.
- Use std::sort() with the comparator functor to sort the list of people.
- Print the sorted list using a loop.
Code Implementation
1. C++ Try on Compiler
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
// Define a structure to represent a person
struct Person {
string name;
int age;
};
// Custom comparator function
bool comparator(const Person &a, const Person &b) {
// Compare names alphabetically
if (a.name != b.name)
return a.name < b.name;
// If names are the same, compare ages in descending order
return a.age > b.age;
}
int main() {
// List of people
vector<Person> people = {{"Alice", 30}, {"Bob", 25}, {"Alice", 35}, {"Charlie", 20}};
// Sort using the custom comparator
sort(people.begin(), people.end(), comparator);
// Print the sorted list
for (const auto &p : people) {
cout << p.name << " " << p.age << endl;
}
return 0;
}
2. Java Try on Compiler
import java.util.*;
class Person {
String name;
int age;
Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return name + " " + age;
}
}
public class Main {
public static void main(String[] args) {
// List of people
List<Person> people = Arrays.asList(
new Person("Alice", 30),
new Person("Bob", 25),
new Person("Alice", 35),
new Person("Charlie", 20)
);
// Sort using a custom comparator
Collections.sort(people, (a, b) -> {
// Compare names alphabetically
if (!a.name.equals(b.name))
return a.name.compareTo(b.name);
// If names are the same, compare ages in descending order
return b.age - a.age;
});
// Print the sorted list
for (Person p : people) {
System.out.println(p);
}
}
}
3. Python Try on Compiler
# List of people as tuples (name, age)
people = [("Alice", 30), ("Bob", 25), ("Alice", 35), ("Charlie", 20)]
# Custom sort using a lambda function
# Sort by name (ascending) first, then by age (descending)
people.sort(key=lambda x: (x[0], -x[1]))
# Print the sorted list
for person in people:
print(person[0], person[1])
4. Javascript Try on Compiler
// List of people as objects
const people = [
{ name: "Alice", age: 30 },
{ name: "Bob", age: 25 },
{ name: "Alice", age: 35 },
{ name: "Charlie", age: 20 }
];
// Custom comparator function
people.sort((a, b) => {
// Compare names alphabetically
if (a.name !== b.name) {
return a.name.localeCompare(b.name);
}
// If names are the same, compare ages in descending order
return b.age - a.age;
});
// Print the sorted list
people.forEach(person => console.log(person.name, person.age));
Custom Order of Characters
Problem Description: Given a custom order of characters (e.g., order = "cba"), sort an array of strings such that the characters in the strings follow the given order.
Intuition: Since we are given a string order describing the precedence of characters in the desired string, we can store the index of each character in the order string in a map for faster lookups. Then, we can create a comparator whose logic will be to return the character with the smaller index in the order string, as a smaller index indicates that the character should come first in the sorted string.
Approach to solve the Problem:
- Define the custom character order in a string (e.g., "cba").
- Create a mapping from each character to its position in the custom order using an unordered_map.
- Sort the string using a comparator that compares characters based on their positions in the custom order.
- Print the sorted string.
Code Implementation
1. C++ Try on Compiler
#include <iostream>
#include <vector>
#include <algorithm>
#include <unordered_map>
#include <climits> // For INT_MAX
using namespace std;
// Comparator function for custom character ordering
bool compare(char a, char b, const unordered_map<char, int>& order_map) {
return order_map.at(a) < order_map.at(b); // Compare based on custom order
}
int main() {
string order = "cba"; // Custom order of characters
string str = "abcd"; // String to sort
// Create a map to store the custom order
unordered_map<char, int> order_map;
for (int i = 0; i < order.size(); ++i) {
order_map[order[i]] = i;
}
// Assign INT_MAX to characters not in the custom order
for (char c : str) {
if (order_map.find(c) == order_map.end()) {
order_map[c] = str.length(); // Place unlisted characters at the end
}
}
// Sort the string using the custom comparator
sort(str.begin(), str.end(), [&](char a, char b) { return compare(a, b, order_map); });
// Print the sorted string
cout << str << endl; // Output: "cbad"
}
2. Java Try on Compiler
import java.util.*;
public class CustomSort {
public static void main(String[] args) {
String order = "cba"; // Custom order of characters
String str = "abcd"; // String to sort
// Create a map to store the custom order
Map<Character, Integer> orderMap = new HashMap<>();
for (int i = 0; i < order.length(); i++) {
orderMap.put(order.charAt(i), i);
}
// Assign str.length() to characters not in the custom order
for (char c : str.toCharArray()) {
orderMap.putIfAbsent(c, str.length()); // Place unlisted characters at the end
}
// Convert string to character array and sort it using custom comparator
Character[] charArray = str.chars().mapToObj(c -> (char) c).toArray(Character[]::new);
Arrays.sort(charArray, (a, b) -> orderMap.get(a) - orderMap.get(b));
// Build and print the sorted string
StringBuilder sortedStr = new StringBuilder();
for (char c : charArray) {
sortedStr.append(c);
}
System.out.println(sortedStr.toString()); // Output: "cbad"
}
}
3. Python Try on Compiler
def custom_sort(order, string):
# Create a map to store the custom order
order_map = {char: i for i, char in enumerate(order)}
# Assign len(string) to characters not in the custom order
order_map = {char: order_map.get(char, len(string)) for char in string}
# Sort the string using custom order
sorted_str = ''.join(sorted(string, key=lambda x: order_map[x]))
return sorted_str
# Example usage
order = "cba"
string = "abcd"
print(custom_sort(order, string)) # Output: "cbad"
4. Javascript Try on Compiler
function customSort(order, str) {
// Create a map to store the custom order
const orderMap = new Map();
for (let i = 0; i < order.length; i++) {
orderMap.set(order[i], i);
}
// Assign str.length to characters not in the custom order
for (const char of str) {
if (!orderMap.has(char)) {
orderMap.set(char, str.length); // Place unlisted characters at the end
}
}
// Convert string to array, sort using custom comparator, and join back to string
const sortedStr = str.split('').sort((a, b) => orderMap.get(a) - orderMap.get(b)).join('');
return sortedStr;
}
// Example usage
const order = "cba";
const str = "abcd";
console.log(customSort(order, str)); // Output: "cbad"
Sort Points by Distance
Problem Description: Given a list of 2D points, sort them by their distance from the origin (0, 0). If two points are equidistant, sort by their x-coordinate.
Intuition: Since we need to sort points based on their distance from (0,0), we first calculate the distance of each point from the origin. The distance between two points is given by the formula: sqrt((x - x1)² + (y - y1)²),
where (x, y) is the given point and (x1, y1) is (0, 0). This simplifies to: sqrt(x² + y²).
To make the calculation more efficient and avoid using square roots, we can use the squared distance instead, which is: x² + y².
Now, to compare any two points, we simply use this squared distance. The point with the smaller squared distance is considered closer to the origin. In case two points have the same distance, we return the point with the smaller x value.
Approach to solve the Problem:
- Calculate the squared distance from the origin for each point (avoiding square roots for efficiency).
- Define a comparator that compares points first by their squared distance, and if the distances are equal, compares by their x-coordinate.
- Sort the list using the custom comparator.
- Output the sorted points.
Code Implementation
1. C++ Try on Compiler
#include <algorithm>
#include <vector>
#include <iostream>
#include <cmath>
using namespace std;
// Function to calculate the square of the distance from the origin (0, 0)
int distanceSquared(int x, int y) {
return x * x + y * y;
}
int main() {
// List of points (x, y)
vector<pair<int, int>> points = {
{3, 4},
{1, 1},
{2, 2},
{0, 5},
};
// Sorting the points by distance first and then by x-coordinate
sort(points.begin(), points.end(), [](const pair<int, int>& a, const pair<int, int>& b) {
int distA = distanceSquared(a.first, a.second); // Distance of point a
int distB = distanceSquared(b.first, b.second); // Distance of point b
// First compare distances
if (distA == distB) {
// If distances are the same, compare by x-coordinate
return a.first < b.first;
}
return distA < distB;
});
// Output sorted points
for (const auto& p : points) {
cout << "(" << p.first << ", " << p.second << ")\n";
}
return 0;
}
2. Java Try on Compiler
import java.util.*;
public class SortPoints {
// Function to calculate the square of the distance from the origin (0, 0)
public static int distanceSquared(int x, int y) {
return x * x + y * y;
}
public static void main(String[] args) {
// List of points (x, y)
List<int[]> points = new ArrayList<>();
points.add(new int[]{3, 4});
points.add(new int[]{1, 1});
points.add(new int[]{2, 2});
points.add(new int[]{0, 5});
// Sorting the points by distance first and then by x-coordinate
points.sort((a, b) -> {
int distA = distanceSquared(a[0], a[1]);
int distB = distanceSquared(b[0], b[1]);
if (distA == distB) {
return Integer.compare(a[0], b[0]); // Compare by x-coordinate if distances are equal
}
return Integer.compare(distA, distB); // Compare by distance
});
// Output sorted points
for (int[] p : points) {
System.out.println("(" + p[0] + ", " + p[1] + ")");
}
}
}
3. Python Try on Compiler
# Function to calculate the square of the distance from the origin (0, 0)
def distance_squared(x, y):
return x * x + y * y
def main():
# List of points (x, y)
points = [(3, 4), (1, 1), (2, 2), (0, 5)]
# Sorting the points by distance first and then by x-coordinate
points.sort(key=lambda p: (distance_squared(p[0], p[1]), p[0]))
# Output sorted points
for p in points:
print(f"({p[0]}, {p[1]})")
if __name__ == "__main__":
main()
4. Javascript Try on Compiler
// Function to calculate the square of the distance from the origin (0, 0)
function distanceSquared(x, y) {
return x * x + y * y;
}
function main() {
// List of points (x, y)
let points = [
[3, 4],
[1, 1],
[2, 2],
[0, 5]
];
// Sorting the points by distance first and then by x-coordinate
points.sort((a, b) => {
let distA = distanceSquared(a[0], a[1]);
let distB = distanceSquared(b[0], b[1]);
if (distA === distB) {
return a[0] - b[0]; // Compare by x-coordinate if distances are equal
}
return distA - distB; // Compare by distance
});
// Output sorted points
points.forEach(p => console.log(`(${p[0]}, ${p[1]})`));
}
main();
Sort Tasks by Deadlines
Problem Description: Sort a list of tasks by their deadlines (ascending). If two tasks have the same deadline, sort them by priority (higher priority first).
Intuition: We can define a structure or class to represent a task, where each task contains a deadline and a priority. To sort the tasks, we can use a comparator with the following logic:
- If the deadlines of two tasks are the same, return the task with the higher priority.
- If the deadlines are different, return the task with the smaller deadline.
This ensures that tasks are sorted primarily by their deadline and secondarily by priority when deadlines are equal.
Approach to solve the Problem:
- Define a Task structure to store the deadline and priority of each task.
- Create a custom comparator that first compares tasks by deadline, and if deadlines are the same, compares by priority (higher priority first).
- Sort the list using the custom comparator.
- Output the sorted tasks.
Code Implementation
1. C++ Try on Compiler
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
// Task structure to store deadline and priority
struct Task {
int deadline;
int priority;
Task(int d, int p) : deadline(d), priority(p) {}
};
// Custom comparator for sorting tasks
bool taskComparator(const Task& a, const Task& b) {
// First compare by deadline
if (a.deadline == b.deadline) {
// If deadlines are the same, compare by priority (higher priority first)
return a.priority > b.priority;
}
return a.deadline < b.deadline; // Sort by deadline in ascending order
}
int main() {
// List of tasks with deadline and priority
vector<Task> tasks = {Task(3, 5), Task(1, 4), Task(3, 7), Task(2, 6), Task(1, 2)};
// Sort the tasks using the custom comparator
sort(tasks.begin(), tasks.end(), taskComparator);
// Output the sorted tasks
cout << "Sorted Tasks by Deadline and Priority:" << endl;
for (const auto& task : tasks) {
cout << "Deadline: " << task.deadline << ", Priority: " << task.priority << endl;
}
return 0;
}
2. Java Try on Compiler
import java.util.*;
class Task {
int deadline;
int priority;
public Task(int deadline, int priority) {
this.deadline = deadline;
this.priority = priority;
}
@Override
public String toString() {
return "Deadline: " + deadline + ", Priority: " + priority;
}
}
public class TaskSorter {
public static void main(String[] args) {
// List of tasks
List<Task> tasks = new ArrayList<>();
tasks.add(new Task(3, 5));
tasks.add(new Task(1, 4));
tasks.add(new Task(3, 7));
tasks.add(new Task(2, 6));
tasks.add(new Task(1, 2));
// Custom comparator to sort by deadline and priority
Collections.sort(tasks, new Comparator<Task>() {
@Override
public int compare(Task a, Task b) {
// First compare by deadline
if (a.deadline == b.deadline) {
// If deadlines are the same, compare by priority (higher priority first)
return b.priority - a.priority;
}
return a.deadline - b.deadline; // Sort by deadline in ascending order
}
});
// Output the sorted tasks
System.out.println("Sorted Tasks by Deadline and Priority:");
for (Task task : tasks) {
System.out.println(task);
}
}
}
3. Python Try on Compiler
from functools import cmp_to_key
# Task class to store deadline and priority
class Task:
def __init__(self, deadline, priority):
self.deadline = deadline
self.priority = priority
def __str__(self):
return f"Deadline: {self.deadline}, Priority: {self.priority}"
# Custom comparator function
def task_comparator(a, b):
# First compare by deadline
if a.deadline == b.deadline:
# If deadlines are the same, compare by priority (higher priority first)
return b.priority - a.priority
return a.deadline - b.deadline # Sort by deadline in ascending order
# List of tasks
tasks = [Task(3, 5), Task(1, 4), Task(3, 7), Task(2, 6), Task(1, 2)]
# Sort the tasks using the custom comparator
tasks.sort(key=cmp_to_key(task_comparator))
# Output the sorted tasks
print("Sorted Tasks by Deadline and Priority:")
for task in tasks:
print(task)
4. Javascript Try on Compiler
class Task {
constructor(deadline, priority) {
this.deadline = deadline;
this.priority = priority;
}
toString() {
return `Deadline: ${this.deadline}, Priority: ${this.priority}`;
}
}
// Custom comparator function
function taskComparator(a, b) {
// First compare by deadline
if (a.deadline === b.deadline) {
// If deadlines are the same, compare by priority (higher priority first)
return b.priority - a.priority;
}
return a.deadline - b.deadline; // Sort by deadline in ascending order
}
// List of tasks
let tasks = [
new Task(3, 5),
new Task(1, 4),
new Task(3, 7),
new Task(2, 6),
new Task(1, 2)
];
// Sort tasks using the custom comparator
tasks.sort(taskComparator);
// Output the sorted tasks
console.log("Sorted Tasks by Deadline and Priority:");
tasks.forEach(task => console.log(task.toString()));
Sort Strings Based on First Occurrence of 'e'
Problem Description: You are given a list of strings. Your task is to sort the list based on the index of the first occurrence of the character "e" in each string. If a string does not contain the character "e", treat it as if the index is beyond the last position of the string (i.e., a large index like the length of the string).
Intuition: Since we are given a list of strings and need to sort them based on the first occurrence of 'e', the approach is as follows:
- Find the first occurrence index of 'e' in each string.
- If 'e' is not present in a string, consider the length of the string as the first occurrence index, as all other indices will be smaller, and the string will come last by default.
- Create a comparator with the following logic:
- Compare strings based on the first occurrence index of 'e'.
- If two strings have the same index for 'e', maintain their relative order.
This way, the strings will be sorted with the one containing the smallest index of 'e' first.
Approach to solve the Problem:
- Define a function firstEIndex to find the index of the first occurrence of 'e' in a string. If 'e' is not found, return the string's length.
- Create a custom comparator compareByEIndex that compares strings based on the first occurrence index of 'e', using the firstEIndex function.
- Sort the list of strings using sort() with the custom comparator, and then print the sorted strings.
Code Implementation
1. C++ Try on Compiler
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
using namespace std;
// Custom comparator to compare based on the first occurrence of 'e'
int firstEIndex(const string& s) {
size_t idx = s.find('e');
return idx == string::npos ? s.length() : idx; // Return length if 'e' is not found
}
// Custom comparator for sorting
bool compareByEIndex(const string& a, const string& b) {
return firstEIndex(a) < firstEIndex(b);
}
int main() {
vector<string> strings = {"apple", "banana", "grape", "cherry", "kiwi"};
// Sort the strings using the custom comparator
sort(strings.begin(), strings.end(), compareByEIndex);
// Output the sorted strings
cout << "Sorted strings based on the first occurrence of 'e':" << endl;
for (const auto& s : strings) {
cout << s << endl;
}
return 0;
}
2. Java Try on Compiler
import java.util.*;
public class SortByFirstE {
public static void main(String[] args) {
// List of strings
List<String> strings = Arrays.asList("apple", "banana", "grape", "cherry", "kiwi");
// Custom comparator to compare by the first occurrence of 'e'
Collections.sort(strings, new Comparator<String>() {
@Override
public int compare(String a, String b) {
return Integer.compare(firstEIndex(a), firstEIndex(b));
}
// Function to find the first occurrence index of 'e'
private int firstEIndex(String s) {
int index = s.indexOf('e');
return (index == -1) ? s.length() : index; // Return length if 'e' is not found
}
});
// Output the sorted strings
System.out.println("Sorted strings based on the first occurrence of 'e':");
for (String s : strings) {
System.out.println(s);
}
}
}
3. Python Try on Compiler
from functools import cmp_to_key
# Custom comparator function to compare by the first occurrence of 'e'
def first_e_index(s):
idx = s.find('e')
return len(s) if idx == -1 else idx # Return length if 'e' is not found
def compare_by_e(a, b):
return first_e_index(a) - first_e_index(b)
# List of strings
strings = ["apple", "banana", "grape", "cherry", "kiwi"]
# Sort the strings using the custom comparator
strings.sort(key=cmp_to_key(compare_by_e))
# Output the sorted strings
print("Sorted strings based on the first occurrence of 'e':")
for s in strings:
print(s)
4. Javascript Try on Compiler
// Custom comparator function to compare by the first occurrence of 'e'
function firstEIndex(str) {
const index = str.indexOf('e');
return index === -1 ? str.length : index; // Return length if 'e' is not found
}
let strings = ["apple", "banana", "grape", "cherry", "kiwi"];
// Sort the strings using the custom comparator
strings.sort((a, b) => firstEIndex(a) - firstEIndex(b));
// Output the sorted strings
console.log("Sorted strings based on the first occurrence of 'e':");
strings.forEach(s => console.log(s));
Pairs by First Element Ascending, Second Element Descending
Problem Description: Given a list of pairs of integers, sort the list such that:
- The first element of each pair is sorted in ascending order.
- If the first element of two pairs is equal, then sort the pairs by the second element in descending order.
Note - use Priority Queue
Intuition: We need to use a priority queue to solve the problem, we can use the custom comparator to control how pairs of integers are ordered in the priority queue. The comparator compares the pairs first by their first element in ascending order. If two pairs have the same first element, it compares the second element in descending order. This ensures that the priority queue will always prioritize pairs with a smaller first element, and if those are equal, the pair with a larger second element will be prioritized. The priority queue uses the comparator to determine the order when inserting and extracting elements, so that the output follows the desired sorting pattern.
Approach to solve the Problem:
- Define a custom comparator that compares pairs.
- First, compare by the first element in ascending order.
- If the first elements are equal, compare by the second element in descending order.
- Use a priority queue with the custom comparator to store the pairs.
- Insert all pairs into the priority queue.
- Extract and print the pairs from the priority queue in the sorted order.
Note: Use opposite signs in the comparator operator because the priority queue by default implements a max-heap, where the largest element has the highest priority. To achieve an ascending order sort for the first element and descending order for the second, the comparator must reverse the natural order. For the first element, we return a.first > b.first to ensure that smaller first elements come first. For the second element, we return a.second < b.second to ensure that larger second elements come first when the first elements are equal. This reverses the default max-heap behavior, achieving the desired sorting order.
Code Implementation
1. C++ Try on Compiler
#include <iostream>
#include <queue>
#include <vector>
using namespace std;
// Custom comparator for sorting pairs
struct Comparator {
bool operator()(const pair<int, int>& a, const pair<int, int>& b) {
// First, compare based on the first element (ascending order)
if (a.first == b.first) {
// If the first elements are equal, compare the second element (descending order)
return a.second < b.second;
}
return a.first > b.first; // Sort by first element (ascending order)
}
};
int main() {
// List of pairs of integers
vector<pair<int, int>> pairs = {{10, 20}, {5, 25}, {10, 15}, {5, 30}, {15, 10}};
// Priority queue with custom comparator
priority_queue<pair<int, int>, vector<pair<int, int>>, Comparator> pq;
// Insert all pairs into the priority queue
for (const auto& p : pairs) {
pq.push(p);
}
// Extract pairs from the priority queue and print them in the sorted order
cout << "Sorted pairs:" << endl;
while (!pq.empty()) {
cout << "(" << pq.top().first << ", " << pq.top().second << ")" << endl;
pq.pop();
}
return 0;
}
2. Java Try on Compiler
import java.util.*;
public class Main {
// Custom comparator for sorting pairs
static class Comparator implements java.util.Comparator<int[]> {
@Override
public int compare(int[] a, int[] b) {
// First, compare based on the first element (ascending order)
if (a[0] == b[0]) {
// If the first elements are equal, compare the second element (descending order)
return Integer.compare(b[1], a[1]);
}
return Integer.compare(a[0], b[0]); // Sort by first element (ascending order)
}
}
public static void main(String[] args) {
// List of pairs of integers
List<int[]> pairs = new ArrayList<>();
pairs.add(new int[]{10, 20});
pairs.add(new int[]{5, 25});
pairs.add(new int[]{10, 15});
pairs.add(new int[]{5, 30});
pairs.add(new int[]{15, 10});
// Priority queue with custom comparator
PriorityQueue<int[]> pq = new PriorityQueue<>(new Comparator());
// Insert all pairs into the priority queue
for (int[] p : pairs) {
pq.offer(p);
}
// Extract pairs from the priority queue and print them in the sorted order
System.out.println("Sorted pairs:");
while (!pq.isEmpty()) {
int[] pair = pq.poll();
System.out.println("(" + pair[0] + ", " + pair[1] + ")");
}
}
}
3. Python Try on Compiler
import heapq
# Custom comparator for sorting pairs
def comparator(a, b):
# First, compare based on the first element (ascending order)
if a[0] == b[0]:
# If the first elements are equal, compare the second element (descending order)
return b[1] - a[1]
return a[0] - b[0] # Sort by first element (ascending order)
def main():
# List of pairs of integers
pairs = [(10, 20), (5, 25), (10, 15), (5, 30), (15, 10)]
# Use heapq to create a priority queue with the custom comparator
pairs = sorted(pairs, key=lambda x: (x[0], -x[1])) # Sorting directly using sorted()
# Extract pairs and print them in the sorted order
print("Sorted pairs:")
for p in pairs:
print(f"({p[0]}, {p[1]})")
if __name__ == "__main__":
main()
4. Javascript Try on Compiler
// Custom comparator for sorting pairs
function comparator(a, b) {
// First, compare based on the first element (ascending order)
if (a[0] === b[0]) {
// If the first elements are equal, compare the second element (descending order)
return b[1] - a[1];
}
return a[0] - b[0]; // Sort by first element (ascending order)
}
function main() {
// List of pairs of integers
let pairs = [
[10, 20],
[5, 25],
[10, 15],
[5, 30],
[15, 10]
];
// Sort the pairs using the custom comparator
pairs.sort(comparator);
// Extract pairs and print them in the sorted order
console.log("Sorted pairs:");
for (let p of pairs) {
console.log(`(${p[0]}, ${p[1]})`);
}
}
main();