使用二进制搜索算法作为实现二进制插入的基础

时间:2012-09-06 13:14:22

标签: java arrays insert binary sorted

我正在尝试实现二进制插入方法。

目前这个方法非常简单,需要一个参数,在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++; } }

1 个答案:

答案 0 :(得分:1)

您的“可能[]冗余检查”禁止初始插入。第一次位置是-1。

在顶部设置position0,应解决问题。