rein0 2020-01-24
/* 算法: 数组的复制,反转,查找(线性查找,二分查找) */ import java.util.Scanner; public class arrayCopyReverseSearch { public static void main(String[] args) { String[] arr = new String[]{"AA", "BB", "CC", "DD", "EE", "FF"}; //数组的复制 String[] arr1 = new String[arr.length]; for (int i = 0; i < arr.length; i++) { arr1[i] = arr[i]; System.out.print(arr1[i]); } System.out.println(); System.out.println("--------------------------"); //数组的反转 for (int i = 0; i < arr.length / 2; i++) { String temp = arr[i]; arr[i] = arr[arr.length - 1 - i]; arr[arr.length - 1 - i] = temp; } //遍历 for (int i = 0; i < arr.length; i++) { System.out.print(arr[i]); } System.out.println(); System.out.println("--------------------------"); //查找 //1,线性查找 boolean isSearched1 = false; System.out.println("请输入arr1中要查找的元素"); Scanner scan = new Scanner(System.in);//输入要查找的元素 String dest1 = scan.next(); for (int i = 0; i < arr1.length; i++) { if (dest1.equals(arr1[i])) {//即dest=arr1[i] System.out.println("查找成功," + dest1 + "位于数组arr1第" + (i + 1) + "个"); isSearched1 = true; break; } } if (!isSearched1) { System.out.println("很抱歉没有找到"); } //2,二分法查找 //前提:查找的序列必须有序 int[] arr2 = new int[]{-51, -31, -25, -10, 1, 17, 31, 48, 79, 97}; System.out.println("请输入arr2中要查找的元素"); int dest2 = scan.nextInt(); //设置首尾"指针" int head = 0; int end = arr2.length-1; boolean isSearched2 = false; while (head <= end) { int mid = (head + end) / 2; if (dest2 == arr2[mid]) { System.out.println("查找成功," + dest2 + "位于数组arr2第" + mid + "个"); isSearched2 = true; break; } else if (dest2 < arr2[mid]) { end = mid - 1;//若目标数<"中位数",则调整尾指针 } else { head = mid + 1;//若目标数>"中位数",则调整头指针 } } if (!isSearched2) { System.out.println("很抱歉没有找到"); } } }