CS61B Homework8 作业回顾(附代码)

一开始在mergeSortedQueues()中想到的是用nth()方法通过count i和j来对比q1和q2中值的大小,也能做出来。后面开始计时之后发现这个方法特别慢,因为每调用一次nth(n)方法,他都要进行n次循环,大大增加了计算次数。后来就干脆用front()得到的值进行对比,再用dequeue()和enqueue()方法。Linkedlist有remove first node的操作,但如果是Array的话就要用到计数器count或者下标了。

Stable or Not?
mergesort()每次从q1和q2中取出front()对比,元素相等时会优先将q1的元素enqueue到新队列,因此这种sort is not stable.
quickSort()中遇到与pivot相同元素时会将元素enqueue到qEqual中,因此这种sort is stable.



package com.homework8;/* ListSorts.java */

import com.homework8.list.*;

import java.util.Random;

public class ListSorts {

  private final static int SORTSIZE = 100;

  /**
   *  makeQueueOfQueues() makes a queue of queues, each containing one item
   *  of q.  Upon completion of this method, q is empty.
   *  @param q is a LinkedQueue of objects.
   *  @return a LinkedQueue containing LinkedQueue objects, each of which
   *    contains one object from q.
   **/
  public static LinkedQueue makeQueueOfQueues(LinkedQueue q) {
    // Replace the following line with your solution.
//    return null;
      LinkedQueue lq = new LinkedQueue();
      int length = q.size();
      try {
          for (int i = 0; i < length; i++){
              Object item = q.dequeue();
              LinkedQueue newqueue = new LinkedQueue();
              newqueue.enqueue(item);
              lq.enqueue(newqueue);
          }
      } catch (QueueEmptyException e){
          e.printStackTrace();
      }
      return lq;
  }

  /**
   *  mergeSortedQueues() merges two sorted queues into a third.  On completion
   *  of this method, q1 and q2 are empty, and their items have been merged
   *  into the returned queue.
   *  @param q1 is LinkedQueue of Comparable objects, sorted from smallest 
   *    to largest.
   *  @param q2 is LinkedQueue of Comparable objects, sorted from smallest 
   *    to largest.
   *  @return a LinkedQueue containing all the Compa
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值