v_anon:
私はプログラミングに新しいです。私は私がプログラミングを学び始めていることを6ヶ月を持っていると私はいくつかのアルゴリズムで私の自己をテストしようとしています。私は、バイナリサーチアルゴリズムを実装しようとしています。理論的には私が概念を把握しているが、実装に私はいくつかの問題を抱えています。
以下は、アルゴリズムの実装は次のとおりです。
public static boolean binarySearchNumber(int[] numbers, int number) {
Arrays.sort(numbers);
System.out.println(Arrays.toString(numbers));
int lowIndex = 0;
int highIndex = numbers.length;
while(lowIndex!=highIndex) {
int midIndex = (lowIndex+highIndex)/2;
if(numbers[midIndex]==number) {
return true;
} else if(numbers[midIndex]>number) {
lowIndex = midIndex+1;
} else if(numbers[midIndex]<number) {
highIndex = midIndex-1;
}
}
return false;
}
ユニットテスト
@Test
public void testBinarySearchNumber() {
// setup
int[] numbers = new int[] { 1, 3, 55, 8, 22, 9, 11, 0 };
// execute
boolean found = ArrayUtil.binarySearchNumber(numbers, 8);
System.out.println(found);
}
前もって感謝します。
レナート:
他の回答で報告されたエラーを超えて、私は別のものを見つけました:
public static boolean binarySearchNumber(int[] numbers, int number) {
Arrays.sort(numbers);
System.out.println(Arrays.toString(numbers));
int lowIndex = 0;
int highIndex = numbers.length;
while (lowIndex != highIndex) {
int midIndex = (lowIndex + highIndex) / 2;
if (numbers[midIndex] == number) {
return true;
} else if (numbers[midIndex] < number) {
lowIndex = midIndex + 1;
} else if (numbers[midIndex] > number) {
highIndex = midIndex ; // here
}
}
return false;
}
midIndex
配列である、あなたはそれ以外の場合は、あなたがいつもより少ない一つの要素を持つことになり、1減算する必要はありません。
EDIT
エランの答え@によって提案されたように、所望の結果を達成するための別の方法は、if条件の変化です。