四次java上机,难得找了天完整的时间来整理之前写过的代码。
1. Describe a Θ(n lg n)-time algorithm that, given a set S of n integers and another integer x, determines whether or not there exist two elements in S whose sum is exactly x. (Implement exercise 2.3-7.)
2. Implement priority queue.
3. Implement Quicksort and answer the following questions. (1) How many comparisons will Quicksort do on a list of n elements that all have the same value? (2) What are the maximum and minimum number of comparisons will Quicksort do on a list of n elements, give an instance for maximum and minimum case respectively.
4. Implement Randomized Quicksort.
1.先将数组进行排序,因为要求算法的复杂度为Θ(n lg n),所以选择堆排序,或者是归并,快排最差情况不符合要求,所以舍去。而主程序的思路:设置两个指标,一个指向头,一个指向尾,不断向中间移动,如果sum[i]+sum[j]>x,则j--,如果sum[i]+sum[j]<x,则i++,直至两个指标指向同一个数或找到结果。
代码如下:
2.第二题优先队列,用堆结构,我顺便将堆排序也写了,这部分写的比较粗糙,因为数组不可变长,所以实现起来不方便,后来学了容器就容易多了,看起来也没那么多麻烦,因为讲究的是算法,所以就没有再去改。测试用的数组a【0】不放任何数据,下标是从1开始,因为在求孩子节点和父亲节点时,用0进行运算不方便。
代码如下:
接下来实现优先队列,只提供思路:
3、第三题和第四题放在一块写了,核心地方并没有变。主要是在partition函数。以一个数为标准,比它大的放在后面,比它小的放在前面,返回其坐标。