Нужна помощь Начало лаборатории.По поводу сравнения времени выполнения универсальных массивов. - PullRequest
0 голосов
/ 26 сентября 2019

Сравнение времени выполнения списка массивов, статического массива и односвязного списка.

Я начал и закончил три класса.Мне просто нужна помощь в проектировании и реализации клиента:

Чтобы сравнить характеристики времени выполнения, выполните следующие действия:

  • Измерьте количество времени, которое требуется каждой структуре для «обработки».«N items.
  • « процесс »будет определяться как чтение N элементов в структуре и последующее чтение (но не удаление) N элементов из структуры.
  • Элементы должны быть помещены в каждую структурутаким же образом, поместив каждый новый элемент в логический конец структуры.
  • Как только структура будет заполнена N элементами, элементы должны быть прочитаны из каждой структуры путем чтения из логического заголовка структуры(первый элемент добавлен в структуру) к логическому хвосту структуры (последний элемент добавлен в структуру).
  • Чтобы быть справедливым, элементы будут экземплярами класса Integer, где значения находятся в диапазоне от 0 до 99.
  • Чтобы быть справедливым, новый генератор случайных чисел должен быть создан перед заполнением каждой структуры так,что каждая структура будет заполнена одинаковым набором случайных чисел.
  • Значения N должны начинаться с 2, а затем удваиваться для каждого запуска теста (см. пример выходных данных).

В настоящее время у меня есть односвязный список, список массивов и интерфейс списка.Часть выше - это то, с чем я борюсь (мне не нужен полный ответ, просто какой-то фон, который может помочь мне начать):

public interface List<E> {
    //returns the number of elements in this list
    int size();

    /** Returns whether the list is empty */
    boolean isEmpty();

    /** Returns (but does not remove) the element at index i */
    E get(int i) throws IndexOutOfBoundsException;
    /** Replaces the element at index i with e, and returns the replaced 
    element */
    E set(int i, E e) throws IndexOutOfBoundsException;
    /** Inserts element e to be at index i, shifting all subsequent 
    elements after */
    void add(int i, E e) throws IndexOutOfBoundsException;
    /** Removes/returns the element at index i, shifting subsequent 
    elements earlier*/
    E remove(int i) throws IndexOutOfBoundsException;
}

public class SinglyLinkedList<E> {
    //---------------- nested Node class ----------------
    private static class Node<E> {
        private E element; // reference to the element stored at this node
        private Node<E> next; // reference to the subsequent node in the list
        public Node(E e, Node<E> n) {
            element = e;
            next = n;
        }
        public E getElement( ) { return element; }
        public Node<E> getNext( ) { return next; }
        public void setNext(Node<E> n) { next = n; }
    }
    // instance variables of the SinglyLinkedList
    private Node<E> head = null; // head node of the list (or null if 
    empty)
    private Node<E> tail = null; // last node of the list (or null if 
    empty)
    private int size = 0; // number of nodes in the list
    public SinglyLinkedList( ) { } // constructs an initially empty list
    // access methods
    public int size( ) { return size; }
    public boolean isEmpty( ) { return size == 0; }
    public E first( ) { // returns (but does not remove) the first element
        if (isEmpty( )) return null;
            return head.getElement( );
    }
    public E last( ) { // returns (but does not remove) the last element
        if (isEmpty( )) return null;
        return tail.getElement( );
    }
    // update methods
    public void addFirst(E e) { // adds element e to the front of the list
        head = new Node<>(e, head); // create and link a new node
        if (size == 0)
            tail = head; // special case: new node becomes tail also
        size++;
    }
    public void addLast(E e) { // adds element e to the end of the list
    Node<E> newest = new Node<>(e, null); // node will eventually be the tail
        if (isEmpty( ))
            head = newest; // special case: previously empty list
        else
            tail.setNext(newest); // new node after existing tail
        tail = newest; // new node becomes the tail
        size++;
    }
    public E removeFirst( ) { // removes and returns the first element
        if (isEmpty( )) return null; // nothing to remove
        E answer = head.getElement( );
        head = head.getNext( ); // will become null if list had only one node
        size--;
        if (size == 0)
            tail = null; // special case as list is now empty
        return answer;
     }
}
public class ArrayList<E> implements List<E> {
    // instance variables
    public static final int CAPACITY=16; // default array capacity
    private E[ ] data; // generic array used for storage
    private int size = 0; // current number of elements
    // constructors
    public ArrayList( ) { this(CAPACITY); } // constructs list with default capacity
    public ArrayList(int capacity) { // constructs list with given capacity
        data = (E[ ]) new Object[capacity]; // safe cast; compiler may give warning
    }
    // public methods
    //Returns the number of elements in the array list. ∗/
    public int size( ) { return size; }
    //Returns whether the array list is empty. ∗/
    public boolean isEmpty( ) { return size == 0; }
    //Returns (but does not remove) the element at index i. ∗/
    public E get(int i) throws IndexOutOfBoundsException {
        checkIndex(i, size);
        return data[i];
    }
    // Replaces the element at index i with e, and returns the replaced element. ∗/
    public E set(int i, E e) throws IndexOutOfBoundsException {
        checkIndex(i, size);
        E temp = data[i];
        data[i] = e;
        return temp;
    }
    // Inserts element e to be at index i, shifting all subsequent elements later.∗/
    public void add(int i, E e) throws IndexOutOfBoundsException, IllegalStateException {
        checkIndex(i, size + 1);
        if (size == data.length) // not enough capacity
            throw new IllegalStateException("Array is full");
            for (int k=size-1; k >= i; k--) // start by shifting rightmost
                data[k+1] = data[k];
                data[i] = e; // ready to place the new element
                size++;
    }
    //Removes/returns the element at index i, shifting subsequent elements earlier. ∗/
    public E remove(int i) throws IndexOutOfBoundsException {
        checkIndex(i, size);
        E temp = data[i];
        for (int k=i; k < size-1; k++) // shift elements to fill hole
            data[k] = data[k+1];
            data[size-1] = null; // help garbage collection
            size--;
        return temp;
    }
    // utility method
    //Checks whether the given index is in the range [0, n−1]. ∗/
    protected void checkIndex(int i, int n) throws IndexOutOfBoundsException {
        if (i < 0 || i >= n)
            throw new IndexOutOfBoundsException("Illegal index: " + i);
    }
}

Формат ожидаемого результата:

Идеальный формат вывода

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