SlideShare a Scribd company logo
1. Suppose you want to implement an ADT in which you can insert values and retrieve or
remove the item with smallest value. (This ADT is called a priority queue). If forced to choose
between an array implementation and a linked list implementation, which would you choose and
why?
2. Write a recursive function that reads a list of integers from the console and prints them in
reverse order. The function should read until a negative number is encountered. You may only
use one local variable of type int. (So arrays or other aggregate data types are allowed.)
Example: 4 5 6 7 8 9 10 -1
10 9 8 7 6 5 4
3. Repeat question 2 using a local stack rather than recursion.
Solution
import java.util.Scanner;
class Value
{
String name;
int priority;
/** Constructor **/
public Value(String name, int priority)
{
this.name = name;
this.priority = priority;
}
/** toString() **/
public String toString()
{
return "Value Name : "+ name +" Priority : "+ priority;
}
}
/** Class PQ **/
class PQ
{
private Value[] SortedArray;
private int Size, Limit;
/** Constructor **/
public PQ(int Limit)
{
this.Limit = Limit + 1;
SortedArray = new Value[this.Limit];
Size = 0;
}
/** function to clear **/
public void clear()
{
SortedArray = new Value[Limit];
Size = 0;
}
/** function to check if empty **/
public boolean isEmpty()
{
return Size == 0;
}
/** function to check if full **/
public boolean isFull()
{
return Size == Limit - 1;
}
/** function to get Size **/
public int size()
{
return Size;
}
/** function to insert task **/
public void insert(String name, int priority)
{
Value Temp = new Value(name, priority);
SortedArray[++Size] = Temp;
int pos = Size;
while (pos != 1 && Temp.priority > SortedArray[pos/2].priority)
{
SortedArray[pos] = SortedArray[pos/2];
pos /=2;
}
SortedArray[pos] = Temp;
}
/** function to remove task **/
public Value remove()
{
int p, c;
Value item, temp;
if (isEmpty() )
{
System.out.println("array is empty");
return null;
}
temp = SortedArray[1];
item = SortedArray[Size--];
p = 1;
c = 2;
while (c <= Size)
{
if (c < Size && SortedArray[c].priority >SortedArray[c + 1].priority)
c++;
if (temp.priority <=SortedArray[c].priority)
break;
SortedArray[p] = SortedArray[c];
p = c;
c *= 2;
}
SortedArray[p] = temp;
return item;
}
}
public class PQTest
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
PQ pq = new PQ(4 );
pq.insert("A",1);
pq.insert("B",2);
pq.insert("C",10);
pq.insert("D",94);
System.out.println("Value A(32),B(2),C(1),D(94) inserted ");
System.out.println("Value removed "+pq.remove());
}
}
====================================================
Output:
akshay@akshay-Inspiron-3537:~/Chegg$ javac PQTest.java
akshay@akshay-Inspiron-3537:~/Chegg$ java PQTest
Value A(32),B(2),C(1),D(94) inserted
Value removed Value Name : A
Priority : 1
==========================================================
import java.util.*;
public class reverse {
public static void main(String[] args) {
Stack stack = new Stack();
System.out.println("Enter elements");
Scanner sc=new Scanner(System.in);
int num;
while((num=sc.nextInt())>0)
{
stack.push(num);
}
System.out.println("Elements in reverse order");
reverseStack(stack);
for (int i = 0, n = stack.size(); i < n; i++) {
System.out.println(stack.elementAt(i));
}
}
public static void reverseStack(Stack stack) {
if (stack.isEmpty()) {
return;
}
T bottom = popBottom(stack);
reverseStack(stack);
stack.push(bottom);
}
private static T popBottom(Stack stack) {
T top = stack.pop();
if (stack.isEmpty()) {
return top;
} else {
T bottom = popBottom(stack);
stack.push(top);
return bottom;
}
}
}
=============================================
akshay@akshay-Inspiron-3537:~/Chegg$ javac reverse.java
akshay@akshay-Inspiron-3537:~/Chegg$ java reverse
Enter elements
4
5
6
7
8
9
10
-1
Elements in reverse order
10
9
8
7
6
5
4

More Related Content

Similar to 1. Suppose you want to implement an ADT in which you can insert valu.pdf (20)

DOCX
To change this license header, choose License Headers in P.docx
adkinspaige22
 
DOCX
When we first examined the array based and node based implementations.docx
ajoy21
 
PDF
Refer to my progress on this assignment belowIn this problem you w.pdf
arishmarketing21
 
PDF
2.(Sorted list array implementation)This sorted list ADT discussed .pdf
arshin9
 
DOCX
package algs13;import stdlib.;import java.util.Iterator;im.docx
gerardkortney
 
PDF
Aj unit2 notesjavadatastructures
Arthik Daniel
 
PDF
Data Structure
Hitesh Mohapatra
 
DOCX
DataStructures notes
Lakshmi Sarvani Videla
 
DOCX
PQTimer.java A simple driver program to run timing t.docx
joyjonna282
 
PDF
1- The design of a singly-linked list below is a picture of the functi (1).pdf
afgt2012
 
PDF
Implement the interface you wrote for Lab B (EntryWayListInterface)..pdf
rishabjain5053
 
DOCX
cs3381-object oriented programming-ab-manual
karthikeyan411470
 
PDF
STAGE 2 The Methods 65 points Implement all the methods t.pdf
babitasingh698417
 
PDF
DS LAB MANUAL.pdf
Selvaraj Seerangan
 
PDF
1. Design a Java interface called Priority that includes two methods.pdf
feelinggift
 
DOCX
Programs
kulwinderbawa007
 
PDF
Ee693 sept2014quiz1
Gopi Saiteja
 
PDF
For each task, submit your source java code file.(1) Objective Im.pdf
dhavalbl38
 
PDF
Lab02kdfshdfgajhdfgajhdfgajhdfgjhadgfasjhdgfjhasdgfjh.pdf
QalandarBux2
 
PDF
In java , I want you to implement a Data Structure known as a Doubly.pdf
aromalcom
 
To change this license header, choose License Headers in P.docx
adkinspaige22
 
When we first examined the array based and node based implementations.docx
ajoy21
 
Refer to my progress on this assignment belowIn this problem you w.pdf
arishmarketing21
 
2.(Sorted list array implementation)This sorted list ADT discussed .pdf
arshin9
 
package algs13;import stdlib.;import java.util.Iterator;im.docx
gerardkortney
 
Aj unit2 notesjavadatastructures
Arthik Daniel
 
Data Structure
Hitesh Mohapatra
 
DataStructures notes
Lakshmi Sarvani Videla
 
PQTimer.java A simple driver program to run timing t.docx
joyjonna282
 
1- The design of a singly-linked list below is a picture of the functi (1).pdf
afgt2012
 
Implement the interface you wrote for Lab B (EntryWayListInterface)..pdf
rishabjain5053
 
cs3381-object oriented programming-ab-manual
karthikeyan411470
 
STAGE 2 The Methods 65 points Implement all the methods t.pdf
babitasingh698417
 
DS LAB MANUAL.pdf
Selvaraj Seerangan
 
1. Design a Java interface called Priority that includes two methods.pdf
feelinggift
 
Ee693 sept2014quiz1
Gopi Saiteja
 
For each task, submit your source java code file.(1) Objective Im.pdf
dhavalbl38
 
Lab02kdfshdfgajhdfgajhdfgajhdfgjhadgfasjhdgfjhasdgfjh.pdf
QalandarBux2
 
In java , I want you to implement a Data Structure known as a Doubly.pdf
aromalcom
 

More from forwardcom41 (20)

PDF
Hello!Can someone help me to answer Task4 and Task7Complete T.pdf
forwardcom41
 
PDF
Hey I need help creating this code using Visual Studio (Basic) 2015.pdf
forwardcom41
 
PDF
Given technology today, would it be more feasible than in the pa.pdf
forwardcom41
 
PDF
Explain the difference between a contaminated culture and a mix c.pdf
forwardcom41
 
PDF
Explain in detail how OFDM helps mitigates multipath fading effects..pdf
forwardcom41
 
PDF
Complete a scientific inquiry research using three credible sources..pdf
forwardcom41
 
PDF
Combine the keypad and LCD codes in compliance to the following requ.pdf
forwardcom41
 
PDF
Describe and illustrate the use of a bank reconciliation in controll.pdf
forwardcom41
 
PDF
Why is it important for a trainer (trainers) to understand the commu.pdf
forwardcom41
 
PDF
What are the various portals an enterprise can use What is the func.pdf
forwardcom41
 
PDF
What is the nature of thermal energy What is heat at the atomic lev.pdf
forwardcom41
 
PDF
w Hstory Bookmarks Window Help Apple Bing Google Taho0 NewaDetals MIN.pdf
forwardcom41
 
PDF
Which of the following is not one of the ethical standards included .pdf
forwardcom41
 
PDF
Using the guidance from ASC 855-10-55-1 and 855-10-55-2 Answer the f.pdf
forwardcom41
 
PDF
why we need mixed methodology for researchSolutionMixed metho.pdf
forwardcom41
 
PDF
What property doesnt apply to fluids Newtons second, cons of ene.pdf
forwardcom41
 
PDF
What is the threat to culture by a read-only world, and how do t.pdf
forwardcom41
 
PDF
What is one hypothesis to explain why there are more endemic bird sp.pdf
forwardcom41
 
PDF
What are the ethical tensions in advertisingWho are the responsib.pdf
forwardcom41
 
PDF
Use the following information to answer the next Question. The graph.pdf
forwardcom41
 
Hello!Can someone help me to answer Task4 and Task7Complete T.pdf
forwardcom41
 
Hey I need help creating this code using Visual Studio (Basic) 2015.pdf
forwardcom41
 
Given technology today, would it be more feasible than in the pa.pdf
forwardcom41
 
Explain the difference between a contaminated culture and a mix c.pdf
forwardcom41
 
Explain in detail how OFDM helps mitigates multipath fading effects..pdf
forwardcom41
 
Complete a scientific inquiry research using three credible sources..pdf
forwardcom41
 
Combine the keypad and LCD codes in compliance to the following requ.pdf
forwardcom41
 
Describe and illustrate the use of a bank reconciliation in controll.pdf
forwardcom41
 
Why is it important for a trainer (trainers) to understand the commu.pdf
forwardcom41
 
What are the various portals an enterprise can use What is the func.pdf
forwardcom41
 
What is the nature of thermal energy What is heat at the atomic lev.pdf
forwardcom41
 
w Hstory Bookmarks Window Help Apple Bing Google Taho0 NewaDetals MIN.pdf
forwardcom41
 
Which of the following is not one of the ethical standards included .pdf
forwardcom41
 
Using the guidance from ASC 855-10-55-1 and 855-10-55-2 Answer the f.pdf
forwardcom41
 
why we need mixed methodology for researchSolutionMixed metho.pdf
forwardcom41
 
What property doesnt apply to fluids Newtons second, cons of ene.pdf
forwardcom41
 
What is the threat to culture by a read-only world, and how do t.pdf
forwardcom41
 
What is one hypothesis to explain why there are more endemic bird sp.pdf
forwardcom41
 
What are the ethical tensions in advertisingWho are the responsib.pdf
forwardcom41
 
Use the following information to answer the next Question. The graph.pdf
forwardcom41
 
Ad

Recently uploaded (20)

PDF
Dimensions of Societal Planning in Commonism
StefanMz
 
PPTX
Identifying elements in the story. Arrange the events in the story
geraldineamahido2
 
PPTX
How to Create a PDF Report in Odoo 18 - Odoo Slides
Celine George
 
PPTX
QUARTER 1 WEEK 2 PLOT, POV AND CONFLICTS
KynaParas
 
PDF
Geographical Diversity of India 100 Mcq.pdf/ 7th class new ncert /Social/Samy...
Sandeep Swamy
 
PPTX
PATIENT ASSIGNMENTS AND NURSING CARE RESPONSIBILITIES.pptx
PRADEEP ABOTHU
 
PPTX
care of patient with elimination needs.pptx
Rekhanjali Gupta
 
PDF
Exploring the Different Types of Experimental Research
Thelma Villaflores
 
PDF
CONCURSO DE POESIA “POETUFAS – PASSOS SUAVES PELO VERSO.pdf
Colégio Santa Teresinha
 
PPTX
grade 5 lesson matatag ENGLISH 5_Q1_PPT_WEEK4.pptx
SireQuinn
 
PPTX
PPT-Q1-WK-3-ENGLISH Revised Matatag Grade 3.pptx
reijhongidayawan02
 
PDF
Stokey: A Jewish Village by Rachel Kolsky
History of Stoke Newington
 
PPTX
How to Create Odoo JS Dialog_Popup in Odoo 18
Celine George
 
PDF
The Constitution Review Committee (CRC) has released an updated schedule for ...
nservice241
 
PDF
The History of Phone Numbers in Stoke Newington by Billy Thomas
History of Stoke Newington
 
PDF
Biological Bilingual Glossary Hindi and English Medium
World of Wisdom
 
PPTX
Stereochemistry-Optical Isomerism in organic compoundsptx
Tarannum Nadaf-Mansuri
 
PPTX
Post Dated Cheque(PDC) Management in Odoo 18
Celine George
 
PPTX
A PPT on Alfred Lord Tennyson's Ulysses.
Beena E S
 
PPTX
Universal immunization Programme (UIP).pptx
Vishal Chanalia
 
Dimensions of Societal Planning in Commonism
StefanMz
 
Identifying elements in the story. Arrange the events in the story
geraldineamahido2
 
How to Create a PDF Report in Odoo 18 - Odoo Slides
Celine George
 
QUARTER 1 WEEK 2 PLOT, POV AND CONFLICTS
KynaParas
 
Geographical Diversity of India 100 Mcq.pdf/ 7th class new ncert /Social/Samy...
Sandeep Swamy
 
PATIENT ASSIGNMENTS AND NURSING CARE RESPONSIBILITIES.pptx
PRADEEP ABOTHU
 
care of patient with elimination needs.pptx
Rekhanjali Gupta
 
Exploring the Different Types of Experimental Research
Thelma Villaflores
 
CONCURSO DE POESIA “POETUFAS – PASSOS SUAVES PELO VERSO.pdf
Colégio Santa Teresinha
 
grade 5 lesson matatag ENGLISH 5_Q1_PPT_WEEK4.pptx
SireQuinn
 
PPT-Q1-WK-3-ENGLISH Revised Matatag Grade 3.pptx
reijhongidayawan02
 
Stokey: A Jewish Village by Rachel Kolsky
History of Stoke Newington
 
How to Create Odoo JS Dialog_Popup in Odoo 18
Celine George
 
The Constitution Review Committee (CRC) has released an updated schedule for ...
nservice241
 
The History of Phone Numbers in Stoke Newington by Billy Thomas
History of Stoke Newington
 
Biological Bilingual Glossary Hindi and English Medium
World of Wisdom
 
Stereochemistry-Optical Isomerism in organic compoundsptx
Tarannum Nadaf-Mansuri
 
Post Dated Cheque(PDC) Management in Odoo 18
Celine George
 
A PPT on Alfred Lord Tennyson's Ulysses.
Beena E S
 
Universal immunization Programme (UIP).pptx
Vishal Chanalia
 
Ad

1. Suppose you want to implement an ADT in which you can insert valu.pdf

  • 1. 1. Suppose you want to implement an ADT in which you can insert values and retrieve or remove the item with smallest value. (This ADT is called a priority queue). If forced to choose between an array implementation and a linked list implementation, which would you choose and why? 2. Write a recursive function that reads a list of integers from the console and prints them in reverse order. The function should read until a negative number is encountered. You may only use one local variable of type int. (So arrays or other aggregate data types are allowed.) Example: 4 5 6 7 8 9 10 -1 10 9 8 7 6 5 4 3. Repeat question 2 using a local stack rather than recursion. Solution import java.util.Scanner; class Value { String name; int priority; /** Constructor **/ public Value(String name, int priority) { this.name = name; this.priority = priority; } /** toString() **/ public String toString() { return "Value Name : "+ name +" Priority : "+ priority; }
  • 2. } /** Class PQ **/ class PQ { private Value[] SortedArray; private int Size, Limit; /** Constructor **/ public PQ(int Limit) { this.Limit = Limit + 1; SortedArray = new Value[this.Limit]; Size = 0; } /** function to clear **/ public void clear() { SortedArray = new Value[Limit]; Size = 0; } /** function to check if empty **/ public boolean isEmpty() { return Size == 0; } /** function to check if full **/ public boolean isFull() { return Size == Limit - 1; } /** function to get Size **/ public int size() { return Size; }
  • 3. /** function to insert task **/ public void insert(String name, int priority) { Value Temp = new Value(name, priority); SortedArray[++Size] = Temp; int pos = Size; while (pos != 1 && Temp.priority > SortedArray[pos/2].priority) { SortedArray[pos] = SortedArray[pos/2]; pos /=2; } SortedArray[pos] = Temp; } /** function to remove task **/ public Value remove() { int p, c; Value item, temp; if (isEmpty() ) { System.out.println("array is empty"); return null; } temp = SortedArray[1]; item = SortedArray[Size--]; p = 1; c = 2; while (c <= Size) { if (c < Size && SortedArray[c].priority >SortedArray[c + 1].priority) c++; if (temp.priority <=SortedArray[c].priority) break;
  • 4. SortedArray[p] = SortedArray[c]; p = c; c *= 2; } SortedArray[p] = temp; return item; } } public class PQTest { public static void main(String[] args) { Scanner scan = new Scanner(System.in); PQ pq = new PQ(4 ); pq.insert("A",1); pq.insert("B",2); pq.insert("C",10); pq.insert("D",94); System.out.println("Value A(32),B(2),C(1),D(94) inserted "); System.out.println("Value removed "+pq.remove()); } } ==================================================== Output: akshay@akshay-Inspiron-3537:~/Chegg$ javac PQTest.java akshay@akshay-Inspiron-3537:~/Chegg$ java PQTest Value A(32),B(2),C(1),D(94) inserted Value removed Value Name : A Priority : 1
  • 5. ========================================================== import java.util.*; public class reverse { public static void main(String[] args) { Stack stack = new Stack(); System.out.println("Enter elements"); Scanner sc=new Scanner(System.in); int num; while((num=sc.nextInt())>0) { stack.push(num); } System.out.println("Elements in reverse order"); reverseStack(stack); for (int i = 0, n = stack.size(); i < n; i++) { System.out.println(stack.elementAt(i)); } } public static void reverseStack(Stack stack) { if (stack.isEmpty()) { return; } T bottom = popBottom(stack); reverseStack(stack); stack.push(bottom); } private static T popBottom(Stack stack) { T top = stack.pop(); if (stack.isEmpty()) { return top; } else { T bottom = popBottom(stack);
  • 6. stack.push(top); return bottom; } } } ============================================= akshay@akshay-Inspiron-3537:~/Chegg$ javac reverse.java akshay@akshay-Inspiron-3537:~/Chegg$ java reverse Enter elements 4 5 6 7 8 9 10 -1 Elements in reverse order 10 9 8 7 6 5 4