Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
Java Program to Sort Items By Weight
Next article icon

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 Weight

Input: 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 Queue

The 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 weight
  • Initialize 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' array
  • Now 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 + " ");         }     } } 

Output
TV 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)


Next Article
Java Program to Sort Items By Weight

S

shubhamkumarsingh4957199
Improve
Article Tags :
  • Java
  • Java Programs
  • java-basics
  • Java-Object Oriented
  • Java-Class and Object
  • java-priority-queue
Practice Tags :
  • Java
  • Java-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
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences