Java Program to Sort Items By Weight Last Updated : 29 Dec, 2023 Comments Improve Suggest changes Like Article Like Report Given two array items and weights which denotes items and their respective weights. Both arrays are of equal length. For every index 'i', items[i] and weights[i] represent the ith item name and its weight respectively. Your task is to return a new array of items sorted in decreasing order by their weights. Note: Each item has a unique positive integer weight. Examples of Sorting Items by WeightInput: items = ["Laptop", "TV", "Phone", "Watch"] weights = [500, 1000,250, 50]Output : ["TV", "Laptop", "Phone", "Watch"]Explanation: Here the items are sorted based on their weight in decreasing order Input: items = ["Banana", "Mango", "Apple"] weights = [50, 100, 60]Output : ["Mango", "Apple", "Banana"] Sort Items By Weight by using the Priority QueueThe idea is to put all the items along with their respective weights into a Priority queue and then sort items in decreasing order by their weights using a custom comparator. Follow the steps given below to implement the approach: Create a class named 'Pair' that consists of the item name and its respective weightInitialize a priority queue and use a custom comparator to sort the pairs based on the weight attribute in descending order. Iterate through the items and weights arrays.Create a Pair object for each item with their respective weight and then add them to the priority queue.Initialize a string array named 'ans' with the same length as the 'items' array.Take a variable named 'idx' which will keep track of the current position in the 'ans' arrayNow iterate through the priority queue while it is not empty. In each iteration, it removes a 'Pair' from the priority queue which is nothing but the item with the highest weight. Store the item in the 'ans' array at the 'idx' position. Then, increment the 'idx' for the next iteration.Finally, return the 'ans' array which now contains the items sorted in decreasing order by their weights. Below is the implementation of the above approach. Java // Java Program to Sort Items // By Weight import java.io.*; import java.util.PriorityQueue; // Driver Class public class SortByWeight { // Pair Class // Used to bind item and weight // together public static class Pair { String item; int weight; Pair(String item, int weight) { this.item = item; this.weight = weight; } } public static String[] sort(String[] items, int[] weights) { // initialize a priority queue // it use a custom comparator to sort the pairs // based on the weight // attribute in descending order PriorityQueue<Pair> pq = new PriorityQueue<>( (a, b) -> Integer.compare(b.weight, a.weight)); // add pair in pq for (int i = 0; i < items.length; i++) { pq.add(new Pair(items[i], weights[i])); } // initialize ans array String[] ans = new String[items.length]; // initialize idx int idx = 0; // remove pair and place in ans array // while priority queue is not empty while (!pq.isEmpty()) { // remove pair from pq Pair p = pq.remove(); // add item in ans array ans[idx] = p.item; idx++; } return ans; } // main function public static void main(String[] args) { String[] items = { "Laptop", "TV", "Phone", "Watch" }; int[] weight = { 500, 1000, 250, 50 }; String[] ans = sort(items, weight); for (String x : ans) { System.out.print(x + " "); } } } OutputTV Laptop Phone Watch Complexity of the above program:Time Complexity : O(N * log(N)), Where N is the number of items Space Complexity : O(N) Comment More infoAdvertise with us Next Article Java Program to Sort Items By Weight shubhamkumarsingh4957199 Follow Improve Article Tags : Java Java Programs java-basics Java-Object Oriented Java-Class and Object java-priority-queue +2 More Practice Tags : JavaJava-Class and Object Similar Reads Java Program for Heap Sort Heap sort is a comparison-based sorting technique based on the Binary Heap data structure. It is similar to the selection sort where first find the maximum element and place it at the end. We repeat the same process for the remaining element. Heap Sort in JavaBelow is the implementation of Heap Sort 3 min read Java Program to Sort a HashMap by Keys and Values HashMap<K, V> is a Java Collection and is a part of java.util package. It provides the basic implementation of the Map interface of Java. It stores the data in the form of Key, Value pairs, where the keys must be unique but there is no restriction for values. If we try to insert the duplicate 3 min read Java Program to Sort LinkedList using Comparable In Java, LinkedList is a part of the collection framework provided in java.util package. LinkedList is a linear data structure where all the elements are unsorted in contiguous memory locations. The advantage of LinkedList is it is dynamic and easy to insert and delete any element. We can not access 5 min read Java Program to Sort LinkedHashMap By Values The LinkedHashMap is just like HashMap with an additional feature of maintaining an order of elements inserted into it. HashMap provided the advantage of quick insertion, search, and deletion, but it never maintained the track and order of insertion which the LinkedHashMap provides where the element 3 min read Java Program to Sort 2D Array Across Columns The Vector class implements a growable array of objects. Vectors basically fall in legacy classes but now it is fully compatible with collections. It is found in the java.util package and implements the List interface, so we can use all the methods of List interface here. This program is used to Sor 3 min read Java Program to Sort Objects in ArrayList by Date The foremost tool that strikes is the sort() method to be used for the comparator mechanism of the Collections class which sorts in the decreasing order. Yes if in generic we want to achieve the goal considering the boundary condition where objects to sorted are user-defined then blindly do with Com 6 min read Java Program for Menu Driven Sorting of Array In Java, sorting an array consists of arranging the elements in a particular order, such as ascending or descending. This can be achieved using various algorithms like Bubble Sort, Selection Sort, or Insertion Sort. A menu-driven program allows users to select the desired sorting method dynamically. 7 min read Java Program to Sort the 2D Array Across Rows This program is used to Sort the 2D array Across rows. We will use the concept of vector to sort each row. Vector Vector(): Creates a default vector of the initial capacity is 10. Vector<E> v = new Vector<E>(); Functions we will use in this: 1. removeAll(): The java.util.vector.removeAll 3 min read Java Program For Case Specific Sorting Given a string S consisting of uppercase and lowercase characters. The task is to sort uppercase and lowercase letters separately such that if the "i"th place in the original string had an Uppercase character then it should not have a lowercase character after being sorted and vice versa. it is desc 2 min read Java Program for Counting Sort Counting sort is a sorting technique based on keys between a specific range. It works by counting the number of objects having distinct key values (kind of hashing). Then doing some arithmetic to calculate the position of each object in the output sequence. Java // Java implementation of Counting So 2 min read Like