Java中使用二分法排序

Ailis ·
更新时间:2024-11-14
· 573 次阅读

  具体代码: import java.util.Scanner; //二分法 public class SplitBy2Sort { public static int splitBy2(int[] a, int num) { int low = 0; int high = a.length - 1; int mid; while (true) { // 取中间下标 mid = (low + high) / 2; if (a[mid] == num) { return mid; } else if (low > high) { return -1; } else if (num > a[mid]) { low = mid + 1; System.out.println("下标往右移"); } else if (num < a[mid]) { high = mid - 1; System.out.println("下标往左移"); } } } public static void main(String[] args) { int[] a = { 1, 3, 6, 12, 26, 37, 47, 58, 69, 78, 80, 98, 100, 114, 126,137, 146, 155, 164, 173 }; System.out.println("输入数组为:"); for (int i = 0; i < a.length; i++) System.out.print(a[i] + " "); System.out.println(); System.out.println("输入你寻找的数字:"); Scanner s = new Scanner(System.in); int num = s.nextInt(); int index = splitBy2(a, num); if (index != -1) { System.out.println("数组下标为:" + index); } else { System.out.println("不存在此数字!"); } } }



二分 二分法 排序 JAVA

需要 登录 后方可回复, 如果你还没有账号请 注册新账号