How to implement a binary search algorithm in java
This article shows you how to achieve a binary search algorithm in java, the content is concise and easy to understand, it can definitely brighten your eyes. I hope you can get something through the detailed introduction of this article.
There are two ways to realize the binary search method: while and recursive method.
Public class maxtest {public static void main (String [] args) {/ / # dichotomous search method start#//int [] arrays = {113phae16 24pyrus 218pyrus 218pyrus 23pyrus 8pyrus 6pyrus 215pyrus 213pyrus 21314pyrus 222pr 28pr 4pr 217pr 5pr 12217pct 122pct 12214212117216}; 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]) {temporary = arrays [I]; arrays [I] = arrays [I]; arrays [I] = 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;} / / binary search while to implement 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