请教一下算法第四版中的课后习题问题

Creaglow 2017-01-22 02:14:58
问题是这样的:
Best case. Write a program QuickBest.java that produces a best-case array (with no duplicates) for Quick.sort(): an array of N distinct keys with the property that every partition will produce subarrays that differ in size by at most 1 (the same subarray sizes that would happen for an array of N equal keys). For the purposes of this exercise, ignore the initial shuffle.
想了一会没有思路,但是看了答案依然看不懂
答案是这样的:
public class QuickBest {

// postcondition: a[lo..hi] is best-case input for quicksorting that subarray
private static void best(int[] a, int lo, int hi) {

// precondition: a[lo..hi] contains keys lo to hi, in order
for (int i = lo; i <= hi; i++)
assert a[i] == i;

if (hi <= lo) return;
int mid = lo + (hi - lo) / 2;
best(a, lo, mid-1);
best(a, mid+1, hi);
exch(a, lo, mid);
}

public static int[] best(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = i;
best(a, 0, n-1);
return a;
}

// exchange a[i] and a[j]
private static void exch(int[] a, int i, int j) {
int swap = a[i];
a[i] = a[j];
a[j] = swap;
}


public static void main(String[] args) {
String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
int n = Integer.parseInt(args[0]);
int[] a = best(n);
for (int i = 0; i < n; i++)
// StdOut.println(a[i]);
StdOut.print(alphabet.charAt(a[i]));
StdOut.println();
}
}



可是看不太懂,大神能不能解释一下呢
...全文
279 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
Creaglow 2017-01-22
  • 打赏
  • 举报
回复
引用 1 楼 ryuugu_rena 的回复:
Quick.sort() 快速排序;ignore the initial shuffle. 不用考虑初始化;an array of N distinct keys 长度为N的没有相同元素的可变数组;我就看得懂那么多了,至于快速排序,你要先了解它的思想,然后才好写代码。
谢谢~中文版题目贴上来了
Creaglow 2017-01-22
  • 打赏
  • 举报
回复
引用 2 楼 qq_33133771 的回复:
如果题目是汉语可能会好点...尴尬
中文版题目贴上来了
Creaglow 2017-01-22
  • 打赏
  • 举报
回复
OK,中文版题目是这样的: 最佳情况 编写一段程序来生成使算法2.5(快速排序)中的sort()方法表现最佳的数组(无重复元素):数组大小为N且不包含重复元素,每次切分后两个子数组的大小最多差1(子数组的大小与含有N个相同元素的数组的切分情况相同)。
风雅_乌龟 2017-01-22
  • 打赏
  • 举报
回复
如果题目是汉语可能会好点...尴尬
ryuugu_rena 2017-01-22
  • 打赏
  • 举报
回复
Quick.sort() 快速排序;ignore the initial shuffle. 不用考虑初始化;an array of N distinct keys 长度为N的没有相同元素的可变数组;我就看得懂那么多了,至于快速排序,你要先了解它的思想,然后才好写代码。

62,621

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧