数据结构学习(三):循环队列与数组队列的时间复杂度对比方法

版权声明:文章为作者原创,若要转载请获得作者同意。尊重版权,从你我做起! https://blog.csdn.net/qq_37768971/article/details/88191278

一、实现方法

1.同时对循环队列和数组队列入队、出队opCount次;

2.用两个System.nanoTime来算出中间代码的执行时间;

3.导入import java.util.Random包,并使用Random中的nextInt(max),其中的max是指输入0-max间的随机数

二、具体代码

package IMUHERO;
import java.util.Random;

public class Main {

    public static double TestQueue(Queue<Integer> q,int opCount){
        long startTime =System.nanoTime();
        Random random=new Random();
        for(int i=0;i<opCount;i++){
            q.enqueue(random.nextInt(Integer.MAX_VALUE));
        }
        for (int i=0;i<opCount;i++){
            q.dequeue();
        }
        long endTime=System.nanoTime();
        return (endTime-startTime)/1000000000.0;
    }

    public static void main(String[] args) {
        int opCount=100000;
        ArrayQueue<Integer>arrayQueue=new ArrayQueue<>();
        double Atime=TestQueue(arrayQueue,opCount);
        System.out.println(Atime);

        LoopQueue<Integer>loopQueue=new LoopQueue<>();
        double Ltime=TestQueue(loopQueue,opCount);
        System.out.println(Ltime);

    }
}

三、由于上一节课没有贴出arrayQueue的代码,在此进行补充,同样也是继承Queue这个接口来计算;

package IMUHERO;

public class ArrayQueue<E>implements Queue<E> {
    Array<E> arrayqueue;
    ArrayQueue(int capacity){
        arrayqueue=new Array<>(capacity);
    }
    ArrayQueue(){
        this(10);
    }
    @Override
    public int getSize(){
        return arrayqueue.getSize();
    }

    public int getCapacity(){
        return arrayqueue.getCapacity();
    }
    @Override
    public boolean isEmpty(){
        return arrayqueue.isEmpty();
    }
    @Override//入队
    public void enqueue(E e){
         arrayqueue.addLast(e);
    }
    @Override//出队
    public E dequeue(){
        return arrayqueue.removeFirst();
    }
    @Override
    public E getFront(){
        return arrayqueue.getFirst();
    }
    @Override
    public String toString(){

        StringBuilder res = new StringBuilder();
        res.append(String.format("ArrayQueue: size = %d , capacity = %d\n", arrayqueue.getSize(), arrayqueue.getCapacity()));
        res.append('[');
        for(int i = 0 ; i < arrayqueue.getSize() ; i ++){
            res.append(arrayqueue.get(i));
            if(i != arrayqueue.getSize() - 1)
                res.append(", ");
        }
        res.append(']');
        return res.toString();
    }


}

四、最终结果:

3.9484546
0.0141529

五、结果分析:

由于arrayQueue出队每一个元素的时候都需要把之后所有队列中的元素向前移动一个位置,所以复杂度为O(n),相对于LoopQueue复杂度更高,并且相差倍数非常大。因此在工程中会使用循环队列来减小时间复杂度。

猜你喜欢

转载自blog.csdn.net/qq_37768971/article/details/88191278
今日推荐