本篇文章为大家展示了java中怎么实现一个二分查找法算法,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。
二分查找法有两种实现方式while、递归方法实现
public class maxtest { public static void main(String[] args) { //###################二分查找法start###################//int[] arrays = {113,16,24,22,218,25,23,8,13,6,215,123,218,113,14,222,28,213,4,2,17,5,12,117,15,122,18,26,214,212,117,216}; int temporary; for (int j = 0; j < arrays.length-1; j++) { for (int i = 0; i < arrays.length; i++) { if (arrays.length-1 == i) { break; }else{ if (arrays[i] > arrays[i+1]) { temporary = arrays[i]; arrays[i] = arrays[i+1]; arrays[i+1] = temporary; } } } } for (int i = 0; i < arrays.length; i++) { System.out.print(arrays[i]+" "); } System.out.println("\n调用递归方法结果:"+binarySearch(arrays,0,arrays.length-1,24));//递归方法调用 System.out.println("\n调用while方法结果:"+binarySearch(arrays,24));//while方法调用//###################二分查找法start###################// } //二分查找法递归实现public static int binarySearch(int[] arrays, int start, int end,int des){ int mid=(start+end)/2; if (arrays[mid] == des) { return mid; } if (start >= end) { return -1; }else if (arrays[mid] < des) { return binarySearch(arrays, mid+1, end, des); }else if(arrays[mid] > des){ return binarySearch(arrays, start, mid-1, des); } return -1; } //二分查找法while实现public static int binarySearch(int[] arrays, int des){ int mid=arrays.length/2; if (arrays[mid] == des) { return des; }int low = 0; int high = arrays.length-1; while(low <= high) { int middle = (low + high)/2; if(des == arrays[middle]) { return middle; }else if(des <arrays[middle]) { high = middle - 1; }else { low = middle + 1; } } return -1; }
结果如下:
2 4 5 6 8 12 13 14 15 16 17 18 22 23 24 25 26 28 113 113 117 117 122 123 212 213 214 215 216 218 218 222 调用递归方法结果:14调用while方法结果:14
示意图
上述内容就是java中怎么实现一个二分查找法算法,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注亿速云行业资讯频道。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。