java折半查找简述_折半查找(java版)
package com.yuan.alg;
/**
* @author yuan
*這個程序是演示折半查找的例子。
*該算法是用遞歸實現的。
*前提條件是該數組必須是有序的。
*/
public class a001 {
/**
*
*/
public a001() {
// TODO Auto-generated constructor stub
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] Array={1,4,5,7,8,9,10,90,99,100}; //有序數列
int findvalue=101; //查找值。
//調用遞歸二叉樹查找方法,將結果返回給result。
int result=binarysearch(Array,0,Array.length-1,findvalue);
if(result!=-1) //如果有結果,輸出結果。
{
System.out.println("該數的下標是:"+result);
System.out.println("/n該數是第"+(result+1)+"個數!");
}
else //否則,輸出提示
System.out.println("該值不存在!");
}
/**
* binarysearch方法實現了折半查找的功能,也和二叉樹查找相似。
* 這是一個遞歸二叉樹查找,在性能上有待提高,查找速度很快,特別適合有序的
* 數列的查找。
* 該算法的主旨:通過比較中間數與目標值的大小來改變查找方向。
* 若中間數比目標值大,向前查找;反之,向后查找。
* 不斷執行這個方法,即遞歸,直到中間數與目標值相等;反之,若沒有匹配的數,則返回
* null。
*
* */
public static int binarysearch(int array[],int first,int last,int value)
{
int index;
if(first>last) //first>last,不符合查找的條件。
{
return -1;
}
else
{
int mid=(first+last)/2; //求mid的值,為查找提供條件。
if(value==array[mid]) //值與中間值匹配。
{
index=mid; //接受mid。
}
else if(value
return binarysearch(array,first,mid-1,value);
else //若大,則向后查找。
return binarysearch(array,mid+1,last,value);
}
return index; //返回一個index,即結果。
}
}
總結
以上是生活随笔為你收集整理的java折半查找简述_折半查找(java版)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 超进化物语颜值增加有什么用
- 下一篇: java线程不能重复_Java中多线程重