Java小练习 数组的复制,反转及查找(线性,二分)
/* 算法: 数组的复制,反转,查找(线性查找,二分查找) */ 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("很抱歉没有找到"); } } }
相关推荐
koushr 2020-11-12
jimeshui 2020-11-13
faiculty 2020-08-20
数据与算法之美 2020-07-04
xhao 2020-06-29
wuxiaosi0 2020-06-28
路漫 2020-06-28
数据与算法之美 2020-06-28
田有朋 2020-06-28
xhao 2020-06-28
natloc 2020-06-27
leoaran 2020-06-22
算法改变人生 2020-06-09
nurvnurv 2020-06-07
shenwenjie 2020-06-04
Tips 2020-06-03
只能做防骑 2020-06-01
yuanran0 2020-05-13