을 구현합니다.기초로 이진 검색 알고리즘을 사용하여 내가 진 삽입 방법을 구현하기 위해 노력하고있어 바이너리 삽입
현재이 메서드는 매우 간단합니다. while 루프에서 인수 (이 경우에는 사람의 성을 나타내는 String)보다 큰 요소를 검색하면 한 번 중단됩니다 그것을 찾아 배열의 나머지 부분을 오른쪽으로 이동시킵니다. 그런 다음 인수는 깨는 위치에 삽입됩니다.
바이너리 검색 알고리즘에서 빌려서 삽입 위치를 검색하는 방법으로 변경해 보았습니다. 그러나, 나는 그것을 작동시킬 수 없습니다.
내가 잘못하고있는 것을 알려주시겠습니까?
public void insert(Person person)
{
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++;
}
}
당신은 당신의 문제를 보여줍니다 간단한 예제를 제공 할 수 있습니까? –
우리가 다음과 같이 말한다면 : 'arr.insert (새 Person ("Charles", "Dickens", 23)); arr.insert (새 Person ("Adam", "Bay", 29)); arr.insert (새 사람 ("에단", "파울러", 18));' 나는 성 ("만"...)에 의해 그것들을 배열하는 기대했다; 이 잘 작동 : '문자열이 lastName = person.getLastName(); 제가 에서 INT; for (i = 0; i 0) break; for (int j = numElems; j> i; j--) array [j] = array [j-1]; 배열 [내가] = 사람; numElems ++;' 하지만 속도를 높이고 싶었습니다. –
Nobilis