java - 使用二分查找算法作为基础来实现二分插入

标签 java arrays insert binary sorting

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

目前这个方法非常简单,它需要一个参数,在 while 循环中它搜索一个比参数大的元素(在本例中是一个字符串,是一个人的姓氏),一旦它就中断找到它并将数组的其余部分向右移动。然后将参数插入到中断的位置。

我尝试将其更改为通过借用二分搜索算法来搜索插入位置的算法。但是,我就是无法让它工作。

你能让我知道我做错了什么吗?这是我的代码:

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。

将顶部的 position 设置为 0 应该可以解决问题。

关于java - 使用二分查找算法作为基础来实现二分插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12300948/

相关文章:

sql-server - SQL Server,插入一行锁定整个表

python - Postgres : Is there a way of executing code following a INSERT statement?

java - 如何通过spring 4 resttemplate发送接收到的jsessionid

java - 如何使用 HQL 通过较弱实体的 id 选择较强的实体(即 @MappedSuperclass)?

Python Scikit Learn : 'argument 1 must be a unicode character, 不是列表

arrays - 如何将 String 转换为 [[Int]]

java - SQLite 约束异常 : error code 19: constraint failed

java - 如何以编程方式设置 JAX-WS 客户端的 SSLContext?

java - 将 Hadoop MapReduce 输出写入 2 个平面文件

arrays - vba 数组操作硬编码语法