Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to implement a binary search algorithm in java

2025-02-22 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

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

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report