Java中使用二分法排序

来源:互联网 发布:怪物猎人捏脸数据库 编辑:程序博客网 时间:2024/06/14 12:05
具体代码:

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("不存在此数字!");}}}




0 0
原创粉丝点击