Как использовать приватный статический метод для сортировки очередей с помощью быстрой сортировки - PullRequest
0 голосов
/ 24 апреля 2019

Эта быстрая сортировка должна использовать очередь. Сигнатуры методов не могут быть изменены, и новые методы не допускаются. Они хотят, чтобы я использовал метод закрытого раздела, но он статический void и нет полей класса, поэтому я понятия не имею, как это могло бы помочь алгоритму быстрой сортировки.

Моя попытка, которая просто возвращает пустую очередь, что имеет смысл, но я не знаю, куда идти.

import edu.princeton.cs.algs4.Queue;

public class QuickSort {

    /**
     * Returns a new queue that contains the given queues catenated together.
     * <p>
     * The items in q2 will be catenated after all of the items in q1.
     *
     * @param q1 A Queue of items
     * @param q2 A Queue of items
     * @return A Queue containing the items of
     * q1 followed by the items of q2.
     */
    private static <Item extends Comparable> Queue<Item> catenate(Queue<Item> q1, Queue<Item> q2) {
        Queue<Item> catenated = new Queue<Item>();
        for (Item item : q1) {
            catenated.enqueue(item);
        }
        for (Item item : q2) {
            catenated.enqueue(item);
        }
        return catenated;
    }

    /**
     * Returns a random item from the given queue.
     *
     * @param items A Queue of items
     * @return A random item from items
     */
    private static <Item extends Comparable> Item getRandomItem(Queue<Item> items) {
        int pivotIndex = (int) (Math.random() * items.size());
        Item pivot = null;
        // Walk through the queue to find the item at the given index.
        for (Item item : items) {
            if (pivotIndex == 0) {
                pivot = item;
                break;
            }
            pivotIndex--;
        }
        return pivot;
    }

    /**
     * Partitions the given unsorted queue by pivoting on the given item.
     *
     * @param unsorted A Queue of unsorted items
     * @param pivot    The item to pivot on
     * @param less     An empty Queue. When the function completes, this queue will contain
     *                 all of the items in unsorted that are less than the given pivot.
     * @param equal    An empty Queue. When the function completes, this queue will contain
     *                 all of the items in unsorted that are equal to the given pivot.
     * @param greater  An empty Queue. When the function completes, this queue will contain
     *                 all of the items in unsorted that are greater than the given pivot.
     */
    private static <Item extends Comparable> void partition(
            Queue<Item> unsorted, Item pivot,
            Queue<Item> less, Queue<Item> equal, Queue<Item> greater) {
        Queue<Item> out = unsorted;

        while(!unsorted.isEmpty()){
            Item t = out.dequeue();
            if (t.compareTo(pivot) > 0){
                greater.enqueue(t);
            }else if(t.compareTo(pivot) == 0){
                equal.enqueue(t);
            }else less.enqueue(t);
        }
        quickSort(less);
        quickSort(greater);
       out = catenate(catenate(less,equal), greater);
    }





    /**
     * Returns a Queue that contains the given items sorted from least to greatest.
     *
     * @param items  A Queue of possibly unsorted items
     * @return       A Queue of sorted items
     */
    public static <Item extends Comparable> Queue<Item> quickSort(
            Queue<Item> items) {
        if (items.size() <= 1){
            return items;
        }
       Item ran = getRandomItem(items);
        Queue<Item> less = new Queue<>();
        Queue<Item> more = new Queue<>();
        Queue<Item> equal = new Queue<>();
        partition(items, ran, less, equal, more);
        return items;
    }

    public static void main(String[] args){
        Queue<Integer> non = new Queue<>();
        non.enqueue(108);
        non.enqueue(180);
        non.enqueue(10);
        non.enqueue(810);

        non = quickSort(non);
        System.out.println(non.toString());
    }
}

Выводит пустой список.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...