Algorithm while循环的最大可能迭代次数

Algorithm while循环的最大可能迭代次数,algorithm,data-structures,Algorithm,Data Structures,我的答案是46(不记得是怎么得到的)。我以降序排列了一个数组,并模拟了它 来源:GATE-cs2016问题当我用java运行这个程序时,数组的降序数是256 int count=0; int[] q = new int[] {16,15,14,13,12,11,10,9,8,7,6,5,4,3,2,1}; Queue<Integer> queue = new LinkedList<Integer>(); Stack<Integer&g

我的答案是
46
(不记得是怎么得到的)。我以降序排列了一个数组,并模拟了它


来源:GATE-cs2016问题

当我用java运行这个程序时,数组的降序数是256

    int count=0;
    int[] q = new int[] {16,15,14,13,12,11,10,9,8,7,6,5,4,3,2,1};
    Queue<Integer> queue = new LinkedList<Integer>();
    Stack<Integer> stack = new Stack<Integer>();
    for(int a : q)
    {
        queue.add(a);
    }
    while(!queue.isEmpty())
    {
        if(stack.isEmpty() || stack.peek() <= queue.peek())
        {
            Integer x=queue.remove();   
            stack.push(x);
        }
        else
        {
            Integer x=stack.pop();
            queue.add(x);
        }
        count++;
    }
    System.out.println(count);
int count=0;
int[]q=新的int[]{16,15,14,13,12,11,10,9,8,7,6,5,4,3,2,1};
Queue Queue=new LinkedList();
堆栈=新堆栈();
for(int a:q)
{
加入(a);
}
而(!queue.isEmpty())
{

如果(stack.isEmpty()| | stack.peek()当我用java运行这个程序时,数组的降序数是256

    int count=0;
    int[] q = new int[] {16,15,14,13,12,11,10,9,8,7,6,5,4,3,2,1};
    Queue<Integer> queue = new LinkedList<Integer>();
    Stack<Integer> stack = new Stack<Integer>();
    for(int a : q)
    {
        queue.add(a);
    }
    while(!queue.isEmpty())
    {
        if(stack.isEmpty() || stack.peek() <= queue.peek())
        {
            Integer x=queue.remove();   
            stack.push(x);
        }
        else
        {
            Integer x=stack.pop();
            queue.add(x);
        }
        count++;
    }
    System.out.println(count);
int count=0;
int[]q=新的int[]{16,15,14,13,12,11,10,9,8,7,6,5,4,3,2,1};
Queue Queue=new LinkedList();
堆栈=新堆栈();
for(int a:q)
{
加入(a);
}
而(!queue.isEmpty())
{

if(stack.isEmpty()| stack.peek()这是一个排序设备

它旋转队列(通过堆栈),直到最小的元素被推送到堆栈中。然后,最小的元素保留在那里

此过程将继续处理剩余的N-1个元素,以此类推

如果队列最初被排序,循环只执行N次


如果队列最初按降序排序,则循环执行2N-1+2N-3+…+1=N²次,这是最坏的情况。

这是一个排序设备

它旋转队列(通过堆栈),直到最小的元素被推送到堆栈中。然后,最小的元素保留在那里

此过程将继续处理剩余的N-1个元素,以此类推

如果队列最初被排序,循环只执行N次


如果队列最初是按降序排序的,则循环执行2N-1+2N-3+…+1=N²次,这是最坏的情况。

我觉得读起来很吃力:你能麻烦键入它吗?(使用块引号).你拍摄的阵列和你展示的照片之间有什么联系?我投票结束这个问题,因为以这种方式要求确认并不是一个有趣的问题。@starblue:OP不仅仅是要求确认。另一方面,他被视为展示了他所做的努力,他做到了。这个问题看起来并不琐碎,所以我不支持反对票。根据经验观察,N个数字的最大操作数为N²(最小为N)。此网站用于编程问题,而不是CS作业。我发现这很难阅读:你能麻烦键入它吗?(使用块引号).你拍摄的阵列和你展示的照片之间有什么联系?我投票结束这个问题,因为以这种方式要求确认并不是一个有趣的问题。@starblue:OP不仅仅是要求确认。另一方面,他被视为展示了他所做的努力,他做到了。这个问题看起来并不琐碎,所以我不支持反对票。根据经验观察,N个数字的最大运算次数为N²(最小为N)。此网站用于编程问题,而不是CS作业。