「java入門」Javaでハーフクリリのサンプルコード

サンプルコード:

public class HalfSerach_Startnews24
{
public static void main(String[] args)
{
int [] arr = {3,6,7,9,11,22,35};
int index = halfsearch(arr,11);   //halfsearchメソッドを呼び出す
System.out.println(“インデックス: " + index); //クエリ結果を出力
}

public static int halfsearch(int [] arr,int key) //halfsearchメソッドを定義
{
int min,max,mid;
min = 0;
max = arr.length-1;
mid=(min+max)/2;

while (arr[mid]!=key)
{
if (key>arr[mid])
min=mid+1;
else if (key<arr[mid])   max=mid-1;

if (min>max)
return -1;
mid=(min+max)/2;
}
return mid;
}

Java

Posted by arkgame