Quicksort
Nuts and bolts. A disorganized carpenter has a mixed pile of n nuts and n bolts. The goal is to find the corresponding pairs of nuts and bolts. Each nut fits exactly one bolt and each bolt fits exactly one nut. By fitting a nut and a bolt together, the carpenter can see which one is bigger (but the carpenter cannot compare two nuts or two bolts directly). Design an algorithm for the problem that uses at most proportional to nlogn compares (probabilistically).
无法通过nuts之间/bolts之间比较来区分各自大小,只能通过一个nut和一个bolt的比较来区分大小。使用快排时,从nuts[]中选出一个nut作为比较基准来对bolts[]进行分块,记分块的结果为m。再以bolts[m]为比较基准对nuts[]进行分块,其结果同样为m。递归排序左右两块。当两个数组都排好序后,即完成了配对。
import java.util.Random;
class NB {
int size;
public NB(int size) {
this.size = size;
}
}
class Nut extends NB {
public Nut(int size) {
super(size);
}
}
class Bolt extends NB {
public Bolt(int size) {
super(size);
}
}
public class NutsAndBolts {
private Nut[] nuts;
private Bolt[] bolts;
public NutsAndBolts(Nut[] nuts, Bolt[] bolts) {
this.nuts = nuts;
this.bolts = bolts;
sort(0, nuts.length - 1);
}
private void sort(int left, int right) {
if (left >= right) {
return;
}
int random = new Random().nextInt(right - left + 1) + left;
swap(nuts, left, random);
for (int i = left; i <= right; i++) {
if (bolts[i].size == nuts[left].size) {
swap(bolts, left, i);
break;
}
}
int m = partition(bolts, nuts[left], left, right);
partition(nuts, bolts[m], left, right);
sort(left, m - 1);
sort(m + 1, right);