Interview Questions: Quicksort

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);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值