最近在找工作,经常被问及,所以备份一下。
二分搜索:
冒泡:
BinarySearch 中常见bug:
二分搜索:
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.youkuaiyun.com/longing_chen/archive/2006/06/10/785570.aspx