1. 程式人生 > 其它 >Qt系統學習第二天

Qt系統學習第二天

                北京時間2022年03月13日,晚22:06分。天氣晴朗,多雲,溫度28。今天來實現JAVA二分查詢,二分查詢的前提是陣列有序,核心思想是比較target和array[mid]的關係,如果target大於array[mid]就到右邊找,反之到左邊找。實現方式有兩種:遞迴實現以及迭代實現。

(一)、程式碼實現:

public static void main(String[] args){
int[] array = {0,1,2,3,4,5,6,7};
int[] arrays = {-99,-98,1,3,4,11,15,17};
int index = RecursiveFind(arrays,-111,0,7);

// int indexs = IteratorFind(arrays,-999);
System.out.println("index = "+index);
// System.out.println("indexs = "+indexs);
}
/**
* 遞迴實現
*/
public static int RecursiveFind(int[] array,int target,int start,int end){
int mid = (end+start)/2;
if (start>end || 0>end){
return -1;
}
if (target>array[mid]){

return RecursiveFind(array,target,mid+1,end);
}else if (target<array[mid]){
return RecursiveFind(array,target,start,mid-1);
}else if (target==array[mid]){
return mid;
}else {
return -1;
}
}
/**
* 迭代實現
*/
public static int IteratorFind(int[] array,int target){
int left = 0;

int right = array.length-1;
// 迭代實現使用while迴圈
while (left<=right){
int mid = (right+left)/2;
if (target>array[mid]){
left = mid+1;
}else if (target<array[mid]){
right = mid-1;
}else {
return mid;
}
}
return -1;
}