java常见算法篇【完整版】

news2024/9/28 3:24:06

14-常见算法

基本查找/顺序查找

  • 从0索引依次向后查找

二分查找/折半查找

  • 前提条件:数组中的数据必须是有序的
  • 核心逻辑:每次排除一半的查找范围
    请添加图片描述
    请添加图片描述
package io.xiaoduo.arithmetic;

public class Test1 {
    public static void main(String[] args) {
        int[] arr = {1, 12, 24, 35, 43, 52, 64, 75, 87, 99, 100};
        System.out.println(binarySearch(arr, 75)); // 7
    }

    // 二分查找
    private static int binarySearch(int[] arr, int num) {
        int min = 0;
        int max = arr.length - 1;
        while (true) {
            if (min > max) {
                return -1;
            }
            int mid = (min + max) / 2;
            if (arr[mid] > num) {
                max = mid - 1;
            } else if (arr[mid] < num) {
                min = mid + 1;
            } else {
                return mid;
            }
        }
    }
}

总结

  1. 二分查找的优势
    • 提高查找效率
  2. 二分查找的前提条件
    • 数据必须是有序的,如果数据是乱的,先排序再使用二分查找得到的索引没有实际意义,只能确定当前数字在数组中是否存在,因为排序之后的数字位置已经发生改变
  3. 二分查找的过程
    • min和max表示当前要查找的范围
    • mid是在min和max中间的
    • 如果要查找的元素在mid的左边,缩小范围时,min不变,max等于mid减一
    • 如果要查找的元素在mid的右边,缩小范围是,max不变,min等于mid加一

二分查找改进/插值查找

请添加图片描述

二分查找改进/斐波那契查找

请添加图片描述

分块查找

  • 核心思想:块内无序,块间有序

请添加图片描述

请添加图片描述

package io.xiaoduo.arithmetic;

public class Test2 {
    public static void main(String[] args) {
        // 分块查找
        int[] arr = {7, 10, 13, 19, 16, 20, 27, 22, 30, 40, 36, 43, 50, 48};
        // 第一步分块
        Block b1 = new Block(10, 0, 1);
        Block b2 = new Block(20, 2, 5);
        Block b3 = new Block(40, 6, 10);
        Block b4 = new Block(50, 11, 13);
        Block[] blockArr = {b1, b2, b3, b4};
        // 要查找的元素
        int num = 20;
        // 分块查找算法函数
        int index = blockSearch(blockArr, arr, num);
        System.out.println(index);
    }

    private static int blockSearch(Block[] blockArr, int[] arr, int num) {
        // 找到num属于哪个块
        int indexBlock = findIndexBlock(blockArr, num);
        // 超出块的范围
        if (indexBlock == -1) return -1;
        // 获取该块的开始和结束素引
        int startIndex = blockArr[indexBlock].getStartIndex();
        int endIndex = blockArr[indexBlock].getEndIndex();
        for (int i = startIndex; i <= endIndex; i++) {
            if (arr[i] == num) {
                return i;
            }
        }
        return -1;
    }

    private static int findIndexBlock(Block[] blockArr, int num) {
        for (int i = 0; i < blockArr.length; i++) {
            int max = blockArr[i].getMax();
            if (num <= max) {
                return i;
            }
        }
        return -1;
    }
}

class Block {
    public int max;
    public int startIndex;
    public int endIndex;

    public Block() {
    }

    public Block(int max, int startIndex, int endIndex) {
        this.max = max;
        this.startIndex = startIndex;
        this.endIndex = endIndex;
    }

    public String toString() {
        return "Block{}";
    }

    /**
     * 获取
     *
     * @return max
     */
    public int getMax() {
        return max;
    }

    /**
     * 设置
     *
     * @param max
     */
    public void setMax(int max) {
        this.max = max;
    }

    /**
     * 获取
     *
     * @return startIndex
     */
    public int getStartIndex() {
        return startIndex;
    }

    /**
     * 设置
     *
     * @param startIndex
     */
    public void setStartIndex(int startIndex) {
        this.startIndex = startIndex;
    }

    /**
     * 获取
     *
     * @return endIndex
     */
    public int getEndIndex() {
        return endIndex;
    }

    /**
     * 设置
     *
     * @param endIndex
     */
    public void setEndIndex(int endIndex) {
        this.endIndex = endIndex;
    }
}

扩展的分块查找(无规律的数据)

请添加图片描述

扩展的分块查找(查找时添加数据),可以使用哈希查找

请添加图片描述

总结

  • 七种查找方式:基本查找,二分查找,差值查找,斐波那契查找,分块查找,哈希查找,树表查找

冒泡排序

  • 相邻的元素两两比较,大的放右边,小的放左边
package io.xiaoduo.arithmetic;

public class Test3 {
    public static void main(String[] args) {
        // 冒泡排序
        int[] arr = {2, 1, 6, 4, 7, 3, 8, 5, 9};
        mySort(arr);
        for (int i : arr) {
            System.out.print(i + " ");
        }
    }

    private static void mySort(int[] arr) {
        for (int i = 0; i < arr.length; i++) {
            for (int j = 0; j < arr.length - i - 1; j++) {
                if (arr[j] > arr[j + 1]) {
                    int temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                }
            }
        }
    }
}

选择排序

  • 从0索引开始,拿着每一个素引上的元素跟后面的元素依次比较,小的放前面,大的放后面,以此类推
package io.xiaoduo.arithmetic;

public class Test4 {
    public static void main(String[] args) {
        // 选择排序
        int[] arr = {2, 1, 6, 4, 7, 3, 8, 5, 9, 13, 10, 12, 11};
        mySort(arr);
        for (int i : arr) {
            System.out.print(i + " ");
        }
    }

    private static void mySort(int[] arr) {
        for (int i = 0; i < arr.length - 1; i++) {
            for (int j = i + 1; j < arr.length; j++) {
                if (arr[i] > arr[j]) {
                    int temp = arr[i];
                    arr[i] = arr[j];
                    arr[j] = temp;
                }
            }
        }
    }
}

插入排序

  • 将0索引的元素到N索引的元素看作是有序的,把N+1索引的元素到最后一个当成是无序的,遍历无序的数据,将遍历到的元素插入有序序列中适当的位置,如遇到相同数据,插在后面,N的范围:0~最大索引
package io.xiaoduo.arithmetic;

public class Test5 {
    public static void main(String[] args) {
        // 插入排序
        int[] arr = {2, 1, 6, 4, 7, 3, 8, 5, 9, 13, 10, 12, 11};
        mySort(arr);
    }

    private static void mySort(int[] arr) {
        int startIndex = -1;
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] > arr[i + 1]) {
                startIndex = i + 1;
                break;
            }
        }
        System.out.println(startIndex);
        for (int i = startIndex; i < arr.length; i++) {
            int j = i;
            while (j > 0 && arr[j] < arr[j - 1]) {
                int temp = arr[j];
                arr[j] = arr[j - 1];
                arr[j - 1] = temp;
                j--;
            }
        }
        for (int i : arr) {
            System.out.print(i + " ");
        }
    }
}

递归算法

  • 指方法调用方法本身
  • 核心:找出口,找规律

快速排序

请添加图片描述

  • 开始索引找到比基准值大的和结束索引找到比基准值小的交换,先移动end再移动start

请添加图片描述

  • 开始索引和结束索引相同时将基准数停止位置交换,最后使用递归将基准值左边和右边的依次换算

请添加图片描述

  • 100万数据只排了149毫秒
package io.xiaoduo.arithmetic;

import java.util.Random;

public class Test6 {
    public static void main(String[] args) {
        // 快速排序
        // int[] arr = {7, 2, 1, 6, 4, 3, 8, 5, 9, 13, 10, 12, 11};
        int[] arr = new int[1000000];
        Random r = new Random();
        for (int i = 0; i < arr.length; i++) {
            arr[i] = r.nextInt();
        }
        long start = System.currentTimeMillis();
        quickSort(arr, 0, arr.length - 1);
        long end = System.currentTimeMillis();
        System.out.println(end - start);
        // for (int i : arr) {
        //     System.out.print(i + " ");
        // }
    }

    private static void quickSort(int[] arr, int i, int j) {
        // 开始索引
        int start = i;
        // 结束素引
        int end = j;
        if (start > end) {
            return;
        }
        // 基准数
        int baseNumber = arr[i];
        while (start != end) {
            while (true) {
                if (end <= start || arr[end] < baseNumber) {
                    break;
                }
                end--;
            }
            while (true) {
                if (end <= start || arr[start] > baseNumber) {
                    break;
                }
                start++;
            }
            int temp = arr[start];
            arr[start] = arr[end];
            arr[end] = temp;
        }
        int temp = arr[i];
        arr[i] = arr[start];
        arr[start] = temp;

        quickSort(arr, i, start - 1);
        quickSort(arr, start + 1, j);
    }
}

常见算法的API-Arrays

方法名说明
public static String toString(数组)把数组拼接成一个字符串
public static int binarySearch(数组,查找的元素)二分查找法查找元素
public static int[] copyOf(原数组,新数组长度)拷贝数组
public static int[] copyOfRange(原数组,起始索引,结束索引)范围拷贝数组
public static void fill(数组,元素)填充数组
public static void sort(数组)按照默认方式进行排序
public static void sort(数组,排序规则)按照指定规则排序

Lambda表达式

  • Lambda表达式是JDK8开始后的一种新语法形式

  • 例如 ( ) -> {}

  • Arrays.sort(arr, (Integer o1, Integer o2) -> {
        return o2 - o1;
    });
    
  • Lambda表达式可以用来简化匿名内部类的书写

  • Lambda表达式只能简化函数式接口的匿名内部类的写法

  • 函数式接口:有且仅有一个抽象方法的接口叫做函数式接口,接口上方可以加@FunctionalInterface注解

  • 和 js 的箭头函数写法很像,省略写法和箭头函数一样

其他

  • 字符串方法s1.compareTo(s2)返回int,-1表示s1小于s2, 遍历字符串ascall码表依次比较

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/712188.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

2023年10个最佳商业WordPress主题(经过测试和专家挑选)

正在寻找最好的商业WordPress主题&#xff1f; 为了帮助您找到适合您业务的完美主题&#xff0c;我们浏览并测试了15个最受欢迎的商业WordPress主题……然后将列表缩减为10个&#xff0c;为您提供最好的。 您需要制作一个成功的商业网站&#xff0c;以激发对潜在客户的信任并…

哪个平板电脑触控笔比较好用?便宜好用的触控笔测评

对于现在的iPad用户来说&#xff0c;苹果原装的Pencil绝对是最好的电容笔选择。但因为价格太高&#xff0c;很多人都买不起。所以&#xff0c;在实际应用中&#xff0c;如何选择一个具有高性能高性价比的电容笔就显得尤为重要。本人是一名“苹果粉”&#xff0c;又是一个老资格…

力扣方法总结-----动态规划

提示&#xff1a;文章写完后&#xff0c;目录可以自动生成&#xff0c;如何生成可参考右边的帮助文档 文章目录 一、动态规划二、动态规划五部曲1.确定DP数组的含义2.确定递推公式3.确定初始值4.确定遍历顺序5.举例推导DP数组&#xff0c;打印程序中DP数组日志 三、例子 一、动…

Day 58-59 Naive Bayes算法

代码&#xff1a; package dl;import java.io.FileReader; import java.util.Arrays; import java.util.Random;import weka.core.*;/*** The Naive Bayes algorithm.*/public class NaiveBayes {/*** An inner class to store parameters.*/private class GaussianParameters…

el-tree 展开指定层级 节点

示例&#xff1a;只展开一级节点 代码实现&#xff1a; element UI 文档 html代码 defaultExpandedArr 是重点 需要加node-key <el-tree:props"defaultProps":data"treeData":default-expanded-keys"defaultExpandedArr"node-key"id&q…

第十六章Java多线程常见模式

文章目录 同步模式之保护性暂停带超时版 GuardedObjectjoin 原理多任务版 GuardedObject 异步模式之生产者/消费者模式标准库中的阻塞队列阻塞队列的实现加锁实现 生产者消费者模型的作用是什么 同步模式之保护性暂停 定义 即 Guarded Suspension&#xff0c;用在一个线程等待…

LeetCode_链表_中等_445.两数相加 II

目录 1.题目2.思路3.代码实现&#xff08;Java&#xff09; 1.题目 给你两个非空链表来代表两个非负整数。数字最高位位于链表开始位置。它们的每个节点只存储一位数字。将这两数相加会返回一个新的链表。 你可以假设除了数字 0 之外&#xff0c;这两个数字都不会以零开头。 …

C#异常总结

C#异常总结 定义Try语句异常类创建用户自定义异常搜索调用栈的示例异常抛出 定义 程序中的运行时错误&#xff0c;它违反一个系统约束或应用程序约束&#xff0c;或出现了在正常操作时未预料的情形。 Try语句 指明被异常保护的代码块&#xff0c;并提供代码以处理异常。try由…

ICC2:fixed和locked有什么不同?

如题&#xff0c;physical status中locked与fixed有很多小伙伴会搞混&#xff0c;从实用性的角度来讲这两个并没有什么区别&#xff0c;一是工具都不会更改object这两种属性&#xff0c;二是工具都不会在优化过程中移除这两个属性的object。 所以&#xff0c;唯一的区别在于lo…

【JUC-4】线程池实战应用

线程池 线程池创建方式 Executors创建线程池(不推荐) JDK提供的工具类Execurtors创建线程池(不推荐), 列举几个Executors中创建线程池的方法; 查看Executors的源代码发现, 它创建线程池也是通过 new ThreadPoolExecutor() 来创建线程池的. 当然其中有一些特殊的线程池也不是…

Moka AI产品后观察:HR SaaS迈进AGI时代

在AI这条路上&#xff0c;Moka已经走了很远。如今的Moka Eva是在此前AI模型基础上的更进一步。未来AGI时代&#xff0c;HR SaaS会有更多可能性。 出品|产业家 在AI潮水里&#xff0c;Moka正在加速快跑。 在6月28日的2023夏季新品发布会上&#xff0c;国内首个AI原生HR Saa…

流量卡收货地就是归属地,这是什么意思呢?

我们在网上申请流量卡时&#xff0c;会比较关注流量卡归属地这一问题&#xff0c;据小编了解&#xff0c;目前网上的流量卡归属地有两种模式&#xff0c;接下来&#xff0c;小编一一为大家介绍一下&#xff0c;大家可以根据自己的情况来选择。 ​ 在中国的手机号码都有固定的区…

【MySQL】备份数据(导出数据 / 导入数据)

&#x1f3af;导出数据 1、使用 SELECT ... INTO OUTFILE 语句导出数据 SELECT...INTO OUTFILE 是 MySQL 用于导出数据的语句&#xff0c;它允许将查询结果保存到指定的文件中。 该语句的基本语法如下&#xff1a; SELECT column1, column2, ... INTO OUTFILE file_path …

Kotlin~Template模版方法模式

概念 定义算法骨架、代码模版 角色介绍 Abstract ClassConcrete Class UML 代码实现 abstract class Game {protected abstract fun initialize()protected abstract fun startPlay()protected abstract fun endPlay()// 模版fun play(){initialize()startPlay()endPlay()…

Spring面试题--Spring中事务失效的场景有哪些

Spring中事务失效的场景有哪些&#xff1f; 异常捕获处理 Transactional public void update(Integer from, Integer to, Double money) {try {//转账的用户不能为空Account fromAccount accountDao.selectById(from);//判断用户的钱是否够转账if (fromAccount.getMoney() - …

idea运行项目时右下角一直提示Lombok requires enabled annotation processing

出现这个错误是因为使用了Lombok插件的原因&#xff0c;可能是安装时候没有配置好 Lombok requires enabled annotation processing&#xff1a;翻译过来就是Lombok 需要启用注释处理 解决方案 File -> Settings ->Build,Execution,Deployment -> Compiler ->An…

35岁程序员现状,太真实!

“未来每年&#xff0c;我们将会为社会输送1000名工作10年以上的人才。” 这是之前马云在演讲中提到的关于阿里巴巴这样的大厂老员工的问题。总的来讲就是——“毕业”。 也经常能够看到在各个平台有程序员讲到自己35岁的焦虑。 之前&#xff0c;在某平台上就有一个有意思的…

Redis主从复制模式3

谋权篡位 假设在一个Redis集群中&#xff0c;有一台主机和两台从机构成一个Redis集群。此时因外部原因&#xff0c;导致主机宕机&#xff0c;俗话说 “国不可⼀一日无君&#xff0c;军不可一日无帅”&#xff0c;那么需要从剩余的两台从机中再次选出一台主机&#xff0c;从而来…

【小沐学Unity3d】Unity插件之绳索模拟Obi Rope

文章目录 1、简介2、安装3、示例测试3.1 Chains3.2 Crane3.3 ElectricalWires3.4 FreightLift3.5 Rocker3.6 RopeAndJoints3.7 RopeShowcase 4、简单测试结语 1、简介 https://assetstore.unity.com/packages/tools/physics/obi-rope-55579 Obi 是一款基于粒子的高级物理引擎…

本地部署 Chatbot UI,一个开源的 ChatGPT UI

openchat-ui 0. 什么是 Chatbot UI1. Github 地址2. 本地部署3. (参考)配置文件说明 0. 什么是 Chatbot UI Chatbot UI 是一个用于 AI 模型的开源聊天 UI。适用于 OpenChat 模型。 画面效果展示如下&#xff0c; 1. Github 地址 https://github.com/imoneoi/openchat-ui 2.…