哈哈,在程序里面,查找也是很重要的。下面给出简单的几种查找...
package net.itaem.search; import java.util.Arrays; import java.util.Random; /** * 顺序查找 * */ public class Search { private int[] search = new int[Integer.MAX_VALUE/32]; private Random random = new Random(); public Search(){ for(int i=0; i<Integer.MAX_VALUE/32; i++){ search[i] = i; } } //顺序查找 //逐个遍历 public int iterSearch(int key){ for(int i=0; i<search.length; i++){ if(search[i] == key){ return i; } } //代表没有找到 return -1; } //折半查找 //前提条件:这个带查找集合是已经排序好的集合 public int binarySearch(int key){ //第一步:先排序带查找的数组,测试时,因为数据本身已经排序好了,不需要执行 //Arrays.sort(search); int low = 0; //低位 int high = search.length - 1; //高位 int middle = -1; while(low < high){ middle = (low + high)/2; int var = search[(low + high)/2]; if(key > var){ low = middle + 1; //往大的方向移动一位 }else if(key < var){ high = middle; //往小的方向移动一位 }else{ return middle; //找到了直接返回 } } return middle; } //插值查找 //注意:是插值查找,不是插入排序 public int interpolationSerach(int key){ //前提条件:该集合数组排序好 //第一步:先排序带查找的数组,测试时,因为数据本身已经排序好了,不需要执行 //Arrays.sort(search); int low = 0; //低位 int high = search.length - 1; //高位 int middle = -1; while(low < high){ middle = low + (high-low) * (search[high] - search[low]); //优化middle... middle = (low + high)/2; int var = search[(low + high)/2]; if(key > var){ low = middle + 1; //往大的方向移动一位 }else if(key < var){ high = middle; //往小的方向移动一位 }else{ return middle; //找到了直接返回 } } return middle; } public int fibonacciSearch(int key){ return -1; } public static void main(String[] args) { Search search = new Search(); System.out.println("=====================iterator search================"); System.out.println(99999 + " in " + search.iterSearch(99999)); System.out.println("=================binary serach========================="); System.out.println(99999 + " binary serach " + search.binarySearch(99999)); System.out.println("=================interpolation serach========================="); System.out.println(99999 + " interpolation serach " + search.interpolationSerach(99999)); } }
查找
时间: 2024-11-05 04:57:23