This example demonstrates how to determine the index at which an element should be inserted into a sorted array. Although binarySearch() is used to locate existent elements, it can also be used to determine the insert index for non-existent elements. Specifically, the insertion index is computed in the following way: insert-index = (-return-value)-1
// Create anarray with an ordered list of items
String[] sortedArray = new String[]{"ant", "bat", "cat", "dog"};
// Search for a non-existent item and then insert it
int index = Arrays.binarySearch(sortedArray, "cow");
if (index < 0) {
// Compute the insert index
int insertIndex = -index-1;
// Insert the new item into sortedArray. The example here creates
// a new larger array to hold the new item.
String[] newSortedArray = new String[sortedArray.length+1];
System.arraycopy(sortedArray, 0, newSortedArray, 0, insertIndex);
System.arraycopy(sortedArray, insertIndex,
newSortedArray, insertIndex+1,
sortedArray.length-insertIndex);
newSortedArray[insertIndex] = "cow";
sortedArray = newSortedArray;
}
没有合适的资源?快使用搜索试试~ 我知道了~
insert-element-into-sorted-array.rar_element
共2个文件
txt:2个
1.该资源内容由用户上传,如若侵权请联系客服进行举报
2.虚拟产品一经售出概不退款(资源遇到问题,请及时私信上传者)
2.虚拟产品一经售出概不退款(资源遇到问题,请及时私信上传者)
版权申诉
0 下载量 179 浏览量
2022-09-24
13:33:56
上传
评论
收藏 885B RAR 举报
温馨提示
A Java example to insert element into sorted array
资源推荐
资源详情
资源评论
收起资源包目录
insert-element-into-sorted-array.rar (2个子文件)
www.pudn.com.txt 218B
insert-element-into-sorted-array.txt 1KB
共 2 条
- 1
资源评论
四散
- 粉丝: 48
- 资源: 1万+
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功