有沒有正在學資料結構的?沒學過C,只會Java的我表示演算法好難 ┭┮﹏┭┮,
廢話不多說,分享一個很簡單的二分查找,在有序陣列(從小到大排序)中查找T型別的變數,我就直接用int 型了,陣列第一個元素(下標為0的元素)不使用,實際查找從第二個元素(下標為1的元素)開始,
全部代碼分為兩部分,
1.方法類
1 /* 2 * 二分法在有序陣列中查找變數k 3 */ 4 public class BinarySearch { 5 6 /* 7 * 方法回傳值為要查找的元素下標,若陣列中沒有待查找的元素k,則回傳-1 8 */ 9 int binarySearch(int[] array,int k) { 10 int left,right,mid; 11 final int NotFound=-1; 12 13 left = 1; //初始化左邊界 14 right = array.length-1; //初始化右邊界 15 16 while(left<=right) { 17 mid = (left+right)/2; 18 if(k<array[mid]) { 19 right = mid-1; 20 }else if(k>array[mid]){ 21 left = mid+1; 22 }else { 23 return mid; 24 } 25 } 26 27 return NotFound; 28 } 29 }
2.測驗類
1 /* 2 * 二分查找測驗類 3 */ 4 import java.util.*; 5 public class TestBinarySearch { 6 7 public static void main(String[] args) { 8 9 int[] array = {0,1,6,8,13,24,45,64,76,77,78,90,93}; //初始化陣列,實際內容從第二個數開始,也就是下標為1的數開始 10 int index=-1; //陣列索引 11 12 System.out.print("請輸入你要查找的整數: "); 13 Scanner input=new Scanner(System.in); 14 int intentNum=input.nextInt(); 15 16 BinarySearch bs = new BinarySearch(); 17 int sub=bs.binarySearch(array,intentNum); 18 19 if(sub!=-1) { 20 index = sub; 21 System.out.println(array[index]+"在陣列中的位置是 "+index); 22 }else { 23 System.out.println("沒有找到‘"+intentNum+"’這個數,"); 24 } 25 26 } 27 28 }
測驗類這個隨意更改,binarySearch()方法是核心,
如果這篇文章對你有用的話,希望點個贊,支持一下作者,有什么更好的看法和建議歡迎評論區留言,Bye,下次見!
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/373791.html
標籤:其他
下一篇:A與B的對話之線索二叉樹
