package ch10;
/**
* successful-折半插入排序
* @author songjie
*
*/
public class BinaryInsertSort {
public static <T extends Comparable> boolean binaryInsertSort(T[] t){
if(t==null || t.length <= 1) return true;
for(int i=1 ; i<=t.length-1 ; i++){
T temp = t[i];
int low = 0;
int high = i-1;
while(low <= high){//此次循环之后,low = high+1
int mid = (low+high)/2;
if(temp.compareTo(t[mid]) > 0) low = mid + 1;
else high = mid - 1;
}
for(int j=i-1 ; j>=low ; j--){
t[j+1] = t[j];
}
t[low] = temp;
}
return true;
}
public static void main(String[] args) {
Integer[] arr = new Integer[]{3,5,7,1,3,4};
BinaryInsertSort.<Integer>binaryInsertSort(arr);
for(int i : arr){
System.out.println(i);
}
}
}
用Java泛型实现折半插入排序
最新推荐文章于 2021-10-27 20:10:53 发布