经典算法之折半查找
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 | package 折半查找; import java.util.Scanner; public class BinarySearch { /** * 折半查找:要求查找的数据是线性保存,表中的数据是按照从小到大的顺序排列的 */ public static int source[] = { 6 , 12 , 28 , 37 , 54 , 65 , 69 , 83 , 90 , 92 }; public static int binarySearch( int s[], int n, int key){ int low,high,mid; low = 0 ; high = n- 1 ; while (low <= high) { mid = (low+high)/ 2 ; if (s[mid] == key) { return mid; } else if (s[mid] > key) { high = mid- 1 ; } else { low = mid+ 1 ; } } return - 1 ; } public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println( "请输入关键字" ); int key = input.nextInt(); int pos = binarySearch(source, source.length, key); System.out.println( "输出原始数据:" ); for ( int i = 0 ;i<source.length;i++) { System.out.printf( "%d\t" ,source[i]); } System.out.println(); if (pos >= 0 ) { System.out.printf( "查找成功,该关键字位于数组的第%d个位置\n" ,pos); } else { System.out.println( "查找失败!" ); } } } |
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步