面试中,BubbleSort/BinarySearch 问到的几率真高

最近在找工作,经常被问及,所以备份一下。

二分搜索:
public class BinarySearch {

public static int search(int[] a, int key) {
return binarySearch(a, 0, a.length, key);
}

private static int binarySearch(int[] a,
int fromIndex, int toIndex, int key) {
int low = fromIndex;
int high = toIndex - 1;

while (low <= high) {
int mid = (low + high) >>> 1;
int midVal = a[mid];

if (midVal < key)
low = mid + 1;
else if (midVal > key)
high = mid - 1;
else
return mid; // key found
}
return -(low + 1); // key not found.
}

}
//对测试Array先排序
//Arrays.sort(theArray);


冒泡:
public abstract class BubbleSorter {

protected int length = 0;

protected void doSort() {
if (length <= 1)
return;

for (int nextToLast = length-2; nextToLast >= 0; nextToLast--)
for (int index = 0; index <= nextToLast; index++) {
if (outOfOrder(index))
swap(index);
}
}

protected abstract void swap(int index);
protected abstract boolean outOfOrder(int index);

}

public class IntBubbleSorter extends BubbleSorter {

private int[] array = null;

public void sort(int[] theArray) {
array = theArray;
length = array.length;

doSort();
}

protected void swap(int index) {
int temp = array[index];
array[index] = array[index + 1];
array[index + 1] = temp;
}


protected boolean outOfOrder(int index) {
return (array[index] > array[index + 1]);
}

}


BinarySearch 中常见bug:

6:             int mid =(low + high) / 2;
在一般情况下, 这个语句是不会出错的, 但是, 当low+high的值超过了最大的正int值 (2^31- 1) 的时候, mid会变成负值

那如何解决这个问题?
很简单, 修改这行语句为:

6: int mid = low + ((high - low) / 2);
或者
6: int mid = (low + high) >>> 1;

在c或者c++中, 则可以如下实现:
6: mid = ((unsigned) (low + high)) >> 1;

原文:http://blog.csdn.net/longing_chen/archive/2006/06/10/785570.aspx
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值