zoukankan      html  css  js  c++  java
  • 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("很抱歉没有找到");
            }
        }
    }
  • 相关阅读:
    发送邮件以及数据导出
    GridView的使用(高度封装,不怎么灵活,repeat可替代)
    索引学习(一)
    JVM 学习笔记(二)
    JVM 学习笔记(一)
    JDBC 基础知识总结
    需要学习的点
    The Unified Modeling Language(UML)
    向往2的年代
    SQL 各种连接:内连接,外连接(左外,右外,完全外)
  • 原文地址:https://www.cnblogs.com/xianghaoran/p/12231580.html
Copyright © 2011-2022 走看看