Java集合中二分查找算法实现

19、Java数组操作与自定义集合实现全解析 本文深入解析了Java中数组的操作,包括对基本数据类型和对象数组的排序与搜索方法,同时探讨了如何通过继承抽象类(如AbstractCollection、AbstractSet和AbstractList)来实现自定义集合。文中提供了详细的代码示例和流程图,帮助开发者更好地掌握数组和集合的核心操作与高级应用,从而提升代码的灵活性与性能。 阅读详情

Java集合中二分查找算法实现

Arrays.binarySearch实现了对有序数组特定区间的二分查找,虽然我们觉得很简单,但是阅读源码的确能看到实现这些库的优秀技巧,总是在追求完美和高效。
值得学习的地方有:
(1)边界检查;
(2)求中位数的时候使用位移操作,而不是 x/2;
(3)如果查找的元素不在数组中,通过返回值昭示了应该插入的位置,而不是直接返回-1;

public static int binarySearch(int[] a, int fromIndex, int toIndex,
                                   int key) {
        rangeCheck(a.length, fromIndex, toIndex);
        return binarySearch0(a, fromIndex, toIndex, key);
    }

    // Like public version, but without range checks.
    private static int binarySearch0(int[] a, int fromIndex, int toIndex,
                                     int key) {
        int low = fromIndex;
        int high = toIndex - 1;

        while (low <= high) {
            int mid = (low + high) >>> 1;
            int midVal = a[mid];

            if (midVal < key)
                low = mid + 1;
            else if (midVal > key)
                high = mid - 1;
            else
                return mid; // key found
        }
        return -(low + 1);  // key not found.
    }
 
同样在Collections里面同样有类似的辅助函数,不过是利用迭代器取得特定位置的元素。
public static <T>
    int binarySearch(List<? extends Comparable<? super T>> list, T key) {
        if (list instanceof RandomAccess || list.size()< BINARYSEARCH_THRESHOLD)
            return Collections. indexedBinarySearch(list, key);
        else
            return Collections. iteratorBinarySearch(list, key);
    }


private static <T>
    int indexedBinarySearch(List<? extends Comparable<? super T>> list, T key ) {
        int low = 0;
        int high = list.size()-1;

        while (low <= high) {
            int mid = ( low + high) >>> 1;
            Comparable<? super T> midVal = list.get( mid);
            int cmp = midVal.compareTo( key);

            if ( cmp < 0)
                low = mid + 1;
            else if ( cmp > 0)
                high = mid - 1;
            else
                return mid; // key found
        }
        return -(low + 1);  // key not found
    }

    private static <T>
    int iteratorBinarySearch(List<? extends Comparable<? super T>> list, T key )
    {
        int low = 0;
        int high = list.size()-1;
        ListIterator<? extends Comparable<? super T>> i = list.listIterator();

        while (low <= high) {
            int mid = ( low + high) >>> 1;
            Comparable<? super T> midVal = get(i , mid );
            int cmp = midVal.compareTo( key);

            if ( cmp < 0)
                low = mid + 1;
            else if ( cmp > 0)
                high = mid - 1;
            else
                return mid; // key found
        }
        return -(low + 1);  // key not found
    }

 /**
     * Gets the ith element from the given list by repositioning the specified
     * list listIterator.
     */
    private static <T> T get(ListIterator<? extends T> i, int index) {
        T obj = null;
        int pos = i.nextIndex();
        if (pos <= index) {
            do {
                obj = i.next();//链表移动
            } while ( pos++ < index);
        } else {
            do {
                obj = i.previous();
            } while (-- pos > index);
        }
        return obj;
    }


    




气象数据收集 国家气象信息中心-中国气象数据网 (cma.cn)国家气象信息中心-中国气象数据网 (cma.cn)预报数据:需要定制,收费10万+路面数据同化系统,实时。 阅读详情

相关推荐

[官方培训]22-UE资产优化 Epic 肖月 笔记

Nanite+Lumen目标:面向TA,美术,不影响视觉的前提下,优化运行和编辑效率引擎:UE5.1延迟管线平台:主流PC,Windows 10 with DX12。

Tcohneyn的博客 1587

二分法查找列表元素

从1个没有重复元素的列表中查找1个元素,用二分法非常高效。

kuailedaima的博客 213

FPGA实战:用DDR3和乒乓操作解决视频帧撕裂问题(附Verilog代码)

本文详细介绍了如何利用DDR3内存和乒乓操作架构解决FPGA视频处理中的帧撕裂问题。通过多帧缓存原理、AXI接口配置和自适应乒乓操作设计,有效隔离读写操作,确保视频流稳定传输。文章包含Verilog代码实现和性能优化技巧,适用于工业相机、医疗影像等高速视频处理场景。

m2n3b4v5c6的博客 298

java实现二分查找

java实现二分查找

程序员阿龙的博客 1万+

pyautogui库详细教程,逐行注释(附项目实战:基于图像识别实现崩坏星穹铁道自动化测试)

本文包含了pyautogui的使用方法与常见问题指南,随文附带对游戏实现的自动化项目源码与说明文档

m0_53043024的博客 1万+

超越PSPNet:PPM模块在医疗影像分割中的创新应用实验

本文探讨了PPM模块在医疗影像分割中的创新应用,通过定制化调整和优化策略显著提升分割精度。针对医疗影像的多尺度病灶特点,提出了动态尺度选择和交叉尺度融合模块(CSFM),结合PyTorch实现细节,使小病灶检测召回率提升11.3%。实验显示优化后的模型mIoU达到78.6%,较基线提升9.2个百分点,同时满足实时处理需求。

u9v0w的博客 237

二分查找算法---Java实现

本文主要介绍的是如何使用Java实现二分查找算法

gaoqiandr的博客 2071

第十二章 供水管网水力模型软件介绍

本文介绍了国内外主要供水管网建模软件及其特点,重点分析了某高建模软件V14的创新功能。国际主流软件包括开源的EPANET、商业软件InfoWorksWS、WaterGEMS和MIKEURBAN,各具特色但存在应用局限。某高V14软件实现了管网GIS与模型一体化管理,采用一G多网、一网多模、一模多案、网模合一技术路线,支持全信息模型建立和动态数据更新。其创新点包括水量分配理念革新(精确/模糊匹配、三种用水模式)和首创Web服务功能。通过并发计算、GPU加速等技术优化性能,具有较高性价比。

weixin_45258875的博客 217

list 查找_趣味图解算法之二分查找

大多数程序员在看到"算法"两字的时候,是不是头大如斗。但如果想去大公司发展,在面试时又绕不过算法这座大山。市面上好多讲解算法的书籍(如算法导论)基本上都太学术、太复杂,对初学者很不友好。因此小编准备换了思路,通过图解方法来分析复杂的算法实现,让初学算法朋友们不会再感到那么枯燥。今天小编为读者老爷们带来了第一篇趣味图解算法之二分查找。1、 简介二分查找也叫折半查找,意思每次查找后,查找范围都折半。使...

weixin_39519741的博客 402

展锐 Android 15 无听筒方案删除配置

【代码】展锐 Android 15 无听筒方案删除配置。

m0_60898338的博客 177

wxComboBox类的使用方法及示例代码

其中,parent表示该控件的父窗口,ID_COMBOBOX是该控件的ID,用于在事件处理函数中区分不同的控件,"默认选项"是下拉列表框的默认选项,options是wxArrayString类型的数组,用于存储下拉列表框中的选项,style可以指定wxComboBox的样式。wxComboBox是wxWidgets中的一个常用控件,它可以被用来显示一组在下拉列表框中的选项,并允许用户从中选择一个选项。上述就是wxComboBox类的基本使用方法,使用这个控件可以方便地实现下拉列表框的功能。

学习使你进步。 730

二分算法(java超详细)

二分法,查找算法,时间复杂度

lll123789456hhh的博客 1万+

论文阅读:ICLR 2026 Breaking and Fixing Defenses Against Control-Flow Hijacking in Multi-Agent Systems

该论文首先系统阐述了控制流劫持攻击的核心机理。此类攻击通过操纵多智能体系统的编排机制,诱导系统执行非安全操作,进而实现敏感信息窃取。攻击者将恶意指令伪装成环境错误信息,借助可信代理传递至系统编排器,利用"困惑副手"漏洞绕过传统安全防线。该论文指出,现有防御方案如LlamaFirewall所依赖的对齐检查机制存在根本性局限——安全目标与功能需求之间存在不可调和的内在冲突。该论文的核心贡献体现在攻防两个维度。

CSPhD-winston的博客 505

java 二分查找 排序_排序集合和二分查找

排序集合和二分查找1.有序集合二分查找(也称折半查找)是非常重要和常见的查找算法,在平衡树和排序集合中应用较多。使用二分查找是有前提条件的,首先要保证集合时一个排序集合,只有在排序集合中才能使用二分查找。在各种类型的数据中,一些数据天生就是有顺序的。比如数字,它天生就拥有自然排序的属性。还有一些数据类型,比如字符串,它也有约定俗成的排序规则。在Java语言中,判断一个类型的数据是否具有可排序的属性...

weixin_34010875的博客 386

IDEA的使用指南

IDEA基于java的使用手册,可以最快速的上手,在使用中不断的丰富自己的使用技巧.

lwip-2.0.3

lwip是瑞典计算机科学院(SICS)的Adam Dunkels 开发的一个小型开源的TCP/IP协议栈。实现的重点是在保持TCP协议主要功能的基础上减少对RAM 的占用。

二分查找思想及实现

使用二分查找必须满足集合有序,只有集合有序时才能使用二分 思想:找出中点元素,此时左侧全是小于它的元素,右侧全是大于它的元素,根据需要选择左半边或右半边,直到找到对应元素 实现: // 递归实现 public boolean find(int[] num, int start, int end, int val) { if (start > end) { return false; } int mid = start + (end - start) / 2;

m0_57015193的博客 172

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

hdu 3763 CD(二分查找) Java实现

   题意:求集合A和B中有几个相同的元素,其中集合中元素已经按升序排好,集合的元素个数n&lt;=1000000          分析:集合中的元素已经按升序排好,只要对B中每个元素在A中进行二分查找就解决了。       代码: public static void main(String[] args) { int n,m; //从键盘录入A,B两个集合中的元素个数 ...

Pmithie的博客 359

visio安装包

Microsoft Office Visio 是一款专业的制图软件。利用经过更新的形状、协作工具和数据链接图表,创建专业级图表以简化复杂的信息。

Java实现二分查找法

本教程将介绍Java中的二进制搜索和递归二进制搜索,以及其算法,实现和Java Binary Seach代码示例: Java中的二进制搜索是一种用于在集合中搜索目标值或键的技术。它是一种使用“分而治之”技术搜索密钥的技术。 应用二进制搜索来搜索关键字的集合需要按升序排序。 通常,大多数编程语言都支持用于搜索集合中数据的线性搜索,二进制搜索和哈希技术。我们将在后续教程中学习哈希。 Java中的二进制搜索 线性搜索是一项基本技术。在此技术中,顺序遍历数组,并将每个元素与键进行比较,直到找到键或.

allway2的博客 1万+

java 集合系列、算法

目录 1. 接口与实现分离 2. 迭代器 2. Collection接口 3. 集合框架中的接口 4. 详细的集合 4.1 链表 4.2 数组列表 4.3 散列集 4.4 树集 4.5 队列、双端队列、优先级队列 5. 映射 5.1 映射的基本API 5.2 映射视图 5.3 弱散列映射 5.4 链接散列集与映射 5.5 标识散列映射 6. 算法 6.1 排序 ...

dgh112233的博客 630

各种查找算法实现

1. 顺序查找(Sequential Search),又叫线性查找 2. 二分查找,又叫折半查找 1 package search; 2 3 /** 4 * @author lei 2011-8-17 5 */ 6 public class BinarySearch { 7 /** 8 * 二分查找 9 * ...

dixianmm198686的博客 154

九、集合

一、JAVA集合框架   与现代的数据结构类库的常见情况一样, Java 集合类库也将接口( interface) 与 实 现 (implementation) 分离。  队列通常有两种实现方式: 一种是使用循环数组。另一种是使用链表。  当在程序中使用队列时,一旦构建了集合就不需要知道究竟使用了哪种实现。因此, 只 有在构建集合对象时,使用具体的类才有意义。可以使用接口类型存放集合的引用。...

王文萱的博客 497

java二分查找算法字符串数组_Java 算法——二分查找数组集合关键元素

packagecom.sinosoft;import java.util.*;importjava.util.stream.Stream;/***@authorCreated by xushuyi* @Description* @date 2019/1/17 10:41*/public classArrayTest {public static voidmain(String[] args) {/...

weixin_42500380的博客 490

递归二分查找

import java.util.ArrayList; import java.util.Arrays; import java.util.Scanner; public class ErFen { public static void main(String ards[]) { System.out.println("请输入元素的个数:"); Scanner s=new Scan...

weixin_43141112的博客 113

java基础复习笔记 数据结构_算法与数据结构细节复习笔记(Java实现)

本笔记涉及代码:https://github.com/hackeryang/Algorithms-Fourth-Edition-Exercises1.Java中的length属性是针对数组说的,比如说声明了一个数组,想知道这个数组的长度则用到了length这个属性,例如有个数组int[] a,那么a的长度就是a.length。length()方法是针对字符串String说的,如果想看这个字符串的长...

weixin_39629129的博客 173

通过Java实现快速查找某个元素在有序集合中的位置(二分查找法,又名折半查找法)

前言: 1、二分查找法又叫折半查找法,从名字来看,能大概明白它的算法逻辑 2、二分查找法必须满足被搜索的集合必须是有序的 3、待查找的元素是在集合中真实存在的 算法: 1、二分查找法每次搜索都是按照搜索区域中间位置的元素进行定位,首次搜索时,开始位置为0,结束位置为集合长度-1,中间位置=(开始位置+结束位置)/2 2、如果中间位置的元素正好与待查找的元素相同,则直接返回结果 3、如果中间位置的元素值大于待查找的元素值,则表示待查找元素在集合的左半区域,那么搜索范围将会缩小到原来的一半,右半边的区域将

@峰的博客 2173

【Java】常用集合算法

Collections类中的sort方法可以对实现了List接口的集合进行排序。 Collection.sort(staff); staff.sort(); // 逆序 staff.sort(Comparator.reverseOrder()); 二分查找 i = Collections.binarySearch(c, element); 常用的其他算法 参考 《Java核心技术 卷Ⅰ》 ...

Kaimar的博客 410

java查找算法:二分查找(两种方式)

二分查找算法思想 二分查找针对的是一个有序的数据集合也就是数组(这也成为了二分查找的一个重要局限性),查找思想有点类似分治思想。 每次都通过跟区间的中间元素对比,将待查找的区间缩小为之前的一半,直到找到要查找的元素,或者区间被缩小为0

weixin_54046648的博客 9466
上一篇: Linux使用du和df命令结果不一致
下一篇: 最大流问题(Ford-Fulkerson算法)
vonzhou
博客等级 码龄17年 260粉丝 197原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值