Question

Implement the selection sort algorithm on a Queue of long-type items. Specifically, you are given the...

Implement the selection sort algorithm on a Queue of long-type items. Specifically, you are given the Queue class implementation and you need to write a method that takes a Queue and sorts it using the selection sort idea. The implementation of the Queue class for long data type is given in the lecture slides (the code skeleton including the implementation of the Queue class is provided below for your convenience). You should go over the Queue and use enqueue(), dequeue(), peek(),... methods to sort the items in the Queue.

You must work with the queue, that means you are not allowed to convert the Queue into an array (or some other data structure) and then sort the array. Also, you should write the sorting part that means you cannot call a library sort method on the Queue.

your file to be submitted to Gradescope should be named HW04P2.java.

    

import java.util.NoSuchElementException;

class Queue

{

    private int maxSize;

    private long[] queArray;

    private int front;

    private int rear;

    private int nItems;

    //--------------------------------------------------------------

    public Queue(int s) // constructor

    {

        maxSize = s;

        queArray = new long[maxSize];

        front = 0;

        rear = -1;

        nItems = 0;

    }

    //----------------------------------------------------------------

    public long dequeue() // take item from front of queue

    {

        if (isEmpty())

            throw new NoSuchElementException("Queue is empty");

        long temp = queArray[front++]; // get value and increment front

        if(front == maxSize) // deal with wraparound

            front = 0;

        nItems--; // one less item

        return temp;

    }

    //----------------------------------------------------------------

    public void enqueue(long j) // put item at rear of queue

    {

        if (isFull())

            throw new IllegalStateException("Queue is full");

        if(rear == maxSize-1) // deal with wraparound

            rear = -1;

        queArray[++rear] = j; // increment rear and insert

        nItems++; // one more item

    }

    //--------------------------------------------------------------

    public long peek() // peek at front of queue

    {

        if (isEmpty())

            throw new NoSuchElementException("Queue is empty");

        return queArray[front];

    }

    //--------------------------------------------------------------

    public boolean isEmpty() // true if queue is empty

    {

        return (nItems==0);

    }

    //--------------------------------------------------------------

    public boolean isFull() // true if queue is full

    {

        return (nItems==maxSize);

    }

    //--------------------------------------------------------------

    public int size() // number of items in queue

    {

        return nItems;

    }

    //--------------------------------------------------------------

    public void display()

    {

        System.out.println("************ printing queue ************");

        for(int i=0; i<nItems; i++) {

            long temp = dequeue();

            System.out.println(temp);

            enqueue(temp);

        }

        System.out.println("************ Done ************");

    }

}

public class HW04P2

{

    public static void selectionSortQ(Queue myQ)

    {

        //your implementation

    }

}

Homework Answers

Answer #1
    public static void selectionSortQ(Queue  myQ) 
    { 
        for(int i = 1; i <= myQ.size(); i++) 
        { 
            
            int min_index = findMinIndex(myQ,myQ.size() - i); //t o get index of minimum number 
            insertMinToRear(myQ, min_index); // to insert minimum element to end to end of queue
        } 
    } 
    
    public static int findMinIndex(Queue q, 
                                     int sortIndex) 
    { 
        //this function will return index of smallest element of queue
        int min_index = -1; 
        long min_value = Integer.MAX_VALUE; 
        int size = q.size();
        for (int i = 0; i < size; i++) 
        { 
            long current = q.dequeue(); 
              
      
            // we need to traverse till sortIndex not beyond it 
            if (current <= min_value && i <= sortIndex) 
            { 
                min_index = i; 
                min_value = current; 
            } 
            q.enqueue(current);  
        } 
        //return index of minimum element
        return min_index; 
    }
    public static void insertMinToRear(Queue q ,
                                             int min_index) 
     { 
         //function to insert minimum element to end of Queue
         // dequeue element from queue and if it is not minimum then enqueue it else 
         // after going through all element then enqueue it so that we make sure  order is followed
        long min_value = 0;  
        int size = q.size(); 
        for (int i = 0; i < size; i++) 
        { 
            long current = q.dequeue(); 
            if (i != min_index) 
                q.enqueue(current); //enqueue dequeued element for all non minimum elements
            else
                min_value = current; //store min index element
        } 
            // enqueue minimum element  after checking all elements of queue
            q.enqueue(min_value); 
    } 

necessary comment are provided in code

idea is find smallest element of queue and insert at end.

repeat this for remaining part of queue.

ex: let queue be  1 5 4 2

1) min index =0

after inserting 1 : 5 4 2 1

2) min index =2

after inserting 2 : 5 4 1 2

3) min index = 1

after inserting 4 : 5 1 2 4

4) min index =0

after inserting 2 : 1 2 4 5

Know the answer?
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for?
Ask your own homework help question
Similar Questions
In Java: Initiate empty queue of strings and recreate .isempty, .size, .dequeue, .enqueue methods. //You may...
In Java: Initiate empty queue of strings and recreate .isempty, .size, .dequeue, .enqueue methods. //You may not use the original methods of the stack api to answer. import java.util.NoSuchElementException; import edu.princeton.cs.algs4.Stack; public class StringQueue {    //You may NOT add any more fields to this class.    private Stack stack1;    private Stack stack2;    /**    * Initializes an empty queue.    */    public StringQueue() { //TODO    }    /**    * Returns true if this queue...
You must alter the Queue class you created in L5 to make it a CIRCULAR Queue...
You must alter the Queue class you created in L5 to make it a CIRCULAR Queue class . Call your class Queue. it must be a template class. public class Queue { } I have put a driver program in the module . It is called CircularQueue.java This driver program should then run with your Queue class (no modifications allowed to the driver program). Your Queue class should have at least the following methods: one or more constructors, enqueue, dequeue,...
Please explain code 1 and code 2 for each lines code 1 public class MyQueue {...
Please explain code 1 and code 2 for each lines code 1 public class MyQueue {    public static final int DEFAULT_SIZE = 10;    private Object data[];    private int index; code 2 package test; import java.util.*; /* Class Node */ class Node { protected Object data; protected Node link; /* Constructor */ public Node() { link = null; data = 0; } /* Constructor */ public Node(Object d,Node n) { data = d; link = n; } /*...
Use the TestTime.java/TestTime.cpp le to compare the two queue implementations. Note that enqueue function when implemented...
Use the TestTime.java/TestTime.cpp le to compare the two queue implementations. Note that enqueue function when implemented using an array has O(1) complexity, and when using two arrays has O(n) complexity, where n is the current size of the queue. So, the two stack implementation should take more time, which is substantiated by the experiment (time output). public class TestTime {    public static void main(String[] args) throws Exception {        for (int maxSize = 10000; maxSize <= 50000; maxSize...
Complete the following functions in the Queue.java/Queue.h files (ATTACHED BELOW): a. void enqueue(int val) b. int...
Complete the following functions in the Queue.java/Queue.h files (ATTACHED BELOW): a. void enqueue(int val) b. int dequeue() c. int getSize() public class Queue {    private int maxQueueSize, front, rear, currentSize; private int[] queue;    public Queue(int maxQueueSize) { if (maxQueueSize <= 0) System.out.println("Queue size should be a positive integer."); else { this.maxQueueSize = maxQueueSize; front = rear = 0; currentSize = 0; queue = new int[maxQueueSize]; } }    public void enqueue(int val) { // complete this function }...
Create a class StacktwoPopArr using Arrays, Change the pop function so that two elements get popped...
Create a class StacktwoPopArr using Arrays, Change the pop function so that two elements get popped everytime instead of the one. If there is only one element in the stack, just pop the one element and report that the stack is now empty. If stack is empty, it should just report that stack is empty. All other functions for StackArray remain the same. using java StackArray.java: public class StackArray {       private final int size = 20; //Size of...
Code in Java Create a queue class to store integers and implement following methods: 1) void...
Code in Java Create a queue class to store integers and implement following methods: 1) void enqueue(int num): This method will add an integer to the queue (end of the queue). 2) int dequeue(): This method will return the first item in the queue (First In First Out). 3) void display(): This method will display all items in the queue (First item will be displayed first). 4) Boolean isEmpty(): This method will check the queue and if it is empty,...
can you please explain how to complete all methods in java ? thanks /* Note:   Do...
can you please explain how to complete all methods in java ? thanks /* Note:   Do not add any additional methods, attributes.         Do not modify the given part of the program.         Run your program against the provided Homework2Driver.java for requirements. */ /* Hint:   This Queue implementation will always dequeue from the first element of         the array i.e, elements[0]. Therefore, remember to shift all elements         toward front of the queue after each dequeue. */ public class QueueArray<T>...
The language is Java. Using a singly-linked list, implement the four queue methods enqueue(), dequeue(), peek(),...
The language is Java. Using a singly-linked list, implement the four queue methods enqueue(), dequeue(), peek(), and isEmpty(). For this assignment, enqueue() will be implemented in an unusual manner. That is, in the version of enqueue() we will use, if the element being processed is already in the queue then the element will not be enqueued and the equivalent element already in the queue will be placed at the end of the queue. Additionally, you must implement a circular queue....
Here's the requirement. Write a client program Subset.java that takes a command-line integer k , reads...
Here's the requirement. Write a client program Subset.java that takes a command-line integer k , reads in a sequence of strings from standard input using StdIn.readString() , and prints out exactly k of them, uniformly at random. Each item from the sequence can be printed out at most once. You may assume that 0 k N , where N is the number of string on standard input. The running time of the program must be linear in the size of...