Java基本算法
import java.util.Scanner; public class BinarySearch { /* * 二分查找法 */ public static int binarySearch(int[] a, int x, int n) { int left = 0; int right = n - 1; while (left <= right) { int middle = (left + right) / 2; if (x == a[middle]) return middle; if (x > a[middle]) left = middle + 1; else right = middle - 1; } return -1; } public static void main(String[] args) { Scanner sc = new Scanner(System.in); // 输入数组个数 System.out.println("请输入数组元素的个数:"); int idex = sc.nextInt(); // 生成数组 int[] b = new int[idex]; // 输入元素 System.out.println("请输入元素:"); for (int i = 0; i < b.length; i++) { b[i] = sc.nextInt(); } System.out.println("输入的数组内容为:"); for (int a : b) { System.out.println(a); } System.out.println("---------------------------"); // 排序 System.out.println("数组进行排序后输出为:"); b = sort(b); for (int a : b) { System.out.println(a); } System.out.println("---------------------------"); // 输入要查询的元素 System.out.println("请输入要查询的元素:"); int element = sc.nextInt(); int i = binarySearch(b, element, b.length); System.out.println(i); } // 由小到大排序(进行选择排序) public static int[] sort(int[] a) { for (int i = 0; i < a.length; i++) { for (int j = 0; j < a.length - 1; j++) { if (a[j] > a[j + 1]) { int temp = a[j]; a[j] = a[j + 1]; a[j + 1] = temp; } } } return a; } }