Implement the instance method sort declared below that sorts a Queue<T> (this) using the…
- User
Implement the instance method sort declared below that sorts a Queue (this) using the "insertion sort" algorithm according to the given order. This algorithm repeatedly calls dequeue until this is empty, placing the entries into a temporary queue with insertInOrder, and then finally transferring this temporary object into this. /**
- Sorts {@code this} according to the ordering provided by the
- {@code compare} method from {@code order}.
- @param order
-
code
ordering by which to sort - @updates this
- @requires IS_TOTAL_PREORDER([relation computed by order.compare method])
- @ensures
- perms(this, #this) and
- IS_SORTED(this, [relation computed by order.compare method])
*/ public void sort(Comparator order) {...}
- Assistant
Here is an implementation of the
sortmethod using the insertion sort algorithm:javapublic void sort(Comparator<T> order) { Queue<T> tempQueue = new LinkedList<>(); while (!this.isEmpty()) { T currentEntry = this.dequeue(); insertInOrder(currentEntry, tempQueue, order); } // Transfer the sorted elements back to this queue while (!tempQueue.isEmpty()) { this.enqueue(tempQueue.dequeue()); } } private void insertInOrder(T currentEntry, Queue<T> queue, Comparator<T> order) { if (queue.isEmpty() || order.compare(currentEntry, queue.peek()) <= 0) { // Insert at the front of the queue queue.enqueue(currentEntry); } else { // Find the correct position to insert the currentEntry T frontEntry; do { frontEntry = queue.dequeue(); queue.enqueue(frontEntry); } while (!queue.isEmpty() && order.compare(currentEntry, queue.peek()) > 0); // Insert the currentEntry at the correct position queue.enqueue(currentEntry); } }