zoukankan      html  css  js  c++  java
  • 数组查找

    1.一般查找:

    public class Demo {
    	public static void main(String[] asadscgs) {
    		int[] arr = { -2, 11, 22, 33, 44, 55, 66, 77, 99, 0, -1 };
    		int index = getIndex(arr, -11);
    		System.out.println("index=" + index);
    
    	}
    
    	// 定义功能
    	public static int getIndex(int[] arr, int key) {
    		// 循环遍历数组,在遍历的过程中取出数组的中的值和指定的key进行比较
    		// 相等就找到,返回当前的下标,如果循环都结束了,也没有相等的,
    		// 说明当前指定的数据,在数组中不存在,
    		// 一般只要是程序中关于查找的问题,没有找到统一都返回-1
    		for (int i = 0; i < arr.length; i++) {
    			if (arr[i] == key) {
    				return i;
    			}
    		}
    
    		// 如果循环都结束了,说明根本就没有找到和指定的值相等的数据
    		return -1;
    
    	}
    }
    

      

    2.折半查找:

    public class Demo {
    	public static void main(String[] asadscgs) {
    		// 定义数组
    		int[] arr = { 4, 7, 9, 12, 23, 34, 45, 67 };
    		// 调用自定义的折半查找的函数
    		int index = binarySearch(arr, 34);
    		System.out.println("index=" + index);
    	}
    
    	/*
    	 * 折半查找的方法 1.有没有返回值? 有,想要查找数组中某个数据的下标,所以返回要查找数据的下标 如果数组中没有该数据,则返回-1 2.有没有参数?
    	 * 有,数组和想要查找的数据
    	 */
    	// 自定义折半查找的函数
    	public static int binarySearch(int[] arr, int key) {
    		// 定义三个变量并给初始化值
    		int start = 0;// 头角标
    		int end = arr.length - 1;// 尾角标
    		int min = (start + end) / 2;// 中间角标
    		// 使用循环往复控制折半
    		while (start <= end) {
    			// 对中间的值和指定的值进行比较
    			if (key == arr[min]) {
    				return min;
    			}
    			// 指定的值大于中间的值
    			if (key > arr[min]) {
    				// 头角标向后移动
    				start = min + 1;
    			}
    			// 指定的值小于中间的值
    			if (key < arr[min]) {
    				// 尾角标向前移动
    				end = min - 1;
    			}
    			// 如果头角标和尾角标发生变化,要时刻更新中间角标
    			min = (start + end) / 2;
    		}
    		// 循环结束,说明没有找到指定的数据
    		return -1;
    	}
    }
    

      

  • 相关阅读:
    .net开源工作流ccflow从表数据数据源导入设置
    驰骋开源的asp.net工作流程引擎java工作流 2015 正文 驰骋工作流引擎ccflow6的功能列表
    app:clean classes Exception
    Android Couldn't load BaiduMapSDK
    android okvolley框架搭建
    compileDebugJavaWithJavac
    android重复的文件复制APK META-INF许可证错误记录
    android listview多视图嵌套多视图
    通讯录笔记
    面试总结
  • 原文地址:https://www.cnblogs.com/JiangNian/p/8406342.html
Copyright © 2011-2022 走看看