public class TestSort<O extends Comparable<O>> { private O[] data; public TestSort(O[] data) { this.data = data; }
/** * 递归折中算法 */ public int sortByReturn(int low, int high, O value) { int mid = (low+high)/2; if(value.compareTo(data[mid])<0) { high = mid -1; return sortByReturn(low,high,value); }else if(value.compareTo(data[mid])>0) { low = mid + 1; return sortByReturn(low,high,value); }else { return mid; } }
/** * 循环折中算法 * @param args */ public int sortByWhile(O value) { if(value==null) { return 0; } int low = 0; int high = data.length-1; int mid ; while(low<=high) { mid = (high+low)/2; if(value.compareTo(data[mid])<0) { high = mid-1; }else if(value.compareTo(data[mid])>0) { low = mid+1; }else if(value.compareTo(data[mid])==0) { return mid; } } return -1; }
public static void main(String[] args) { Integer data[] = {1,2,5,7,9,33,43,45,66,78,93}; TestSort<Integer> ts = new TestSort<Integer>(data); System.out.println("sort by while:"+ts.sortByWhile(5)); System.out.println("sort2 by while:"+ts.sortByReturn(0,data.length-1,33)); } } |