/** 冒泡 */
public static void bober(int[] array){
int length = array.length;
for(int i=0;i<length-1;i++){ /** 每两个比较一次,总次数是 length-1 */
for(int j=0;j<length-1-i;j++){ // 每次总有一个最大的找出 -i
if(array[j]>array[j+1]){
int temp = array[j];
array[j] = array[j+1];
array[j+1] = temp;
}
}
}
}
/** 快排 */
public static void quickSort(int[] array,int left,int right){
if(array==null){
return;
}
int length = array.length;
if(length == right){ // 防止输入数组的非下标长度,造成越界
right = right -1;
}
if(left > right){
return;
}
int low = left;
int hight = right;
int key = array[left];
while(low<hight){
while(low<hight && array[hight]>=key){
hight --;
}
array[low] = array[hight];
while(low<hight && array[low]<=key){
low++;
}
array[hight] = array[low];
}
array[low] = key; /** 被比较的数此时应该回到 low 位置 */
quickSort(array,left,low-1);
quickSort(array,low+1,right);
}
/** 二分查找 */
public static int binary(int[] array, int value){
int low = 0;
int high = array.length - 1; // 防止越界
while(low <= high){
int middle = (low + high) / 2;
if(value == array[middle]){
return middle; // 下标
}
if(value > array[middle]){
low = middle + 1;
}
if(value < array[middle]){
high = middle - 1;
}
}
return -1;
}
网友评论