0

バイナリ挿入メソッドを実装しようとしています。

現在、このメソッドは非常に単純で、引数を取ります。whileループでは、引数よりも大きい要素(この場合は人の名前である文字列)を検索し、それを見つけると壊れて、配列の残りの部分を右にシフトします。次に、引数がブレークの位置に挿入されます。

二分探索アルゴリズムを借りて挿入位置を検索するものに変更してみました。しかし、私はそれを機能させることができません。

私が間違っていることを教えてください。これが私のコードです:

パブリックボイドインサート(個人)
{{

String lastName = person.getLastName(); int position = -1; // the position from which the array will be shifted to the right and where the argument will be inserted, will be assigned properly below int lowerBound = 0; int upperBound = numElems - 1; int currIt; if (numElems == 0) array[0] = person; // if array empty insert at first position else { while (true) { currIt = (lowerBound + upperBound) / 2; //the item to compare with int result2 = 0; int result1 = array[currIt].getLastName().compareTo(lastName); if (array[currIt+1] != null) // if the next element is not null, compare the argument to it result2 = array[currIt+1].getLastName().compareTo(lastName); if (currIt == 0 && result1 > 0) // this is when the argument is smaller then the first array element { position = 0; break; } // if the position to insert is the last one, or we have found a suitable position between a smaller and a bigger element else if ( (result1 < 0 && (currIt == numElems-1)) || (result1 < 0 && result2 > 0) ) { position = currIt+1; break; } else { if (result1 < 0) // the place to put it should be in the upper half lowerBound = currIt + 1; else upperBound = currIt - 1; //in the lower half } } } // position has been set to anything else other -1, then we have found our spot, probably a redundant check but useful for debugging if (position != -1) { //shift array to the right and insert element for (int j = numElems; j > position; j--) array[j] = array[j-1]; System.out.println("Inserted an element"); array[position] = person; numElems++; } }

4

1 に答える 1

1

あなたの「おそらく[]冗長チェック」は、最初の挿入を禁止しています。位置は最初は -1 です。

上部に設定positionすると、問題が解決するはずです。0

于 2012-09-06T13:26:36.237 に答える