Java 插入到ArrayList中<;发生率>;使用二进制搜索

Java 插入到ArrayList中<;发生率>;使用二进制搜索,java,search,binary,Java,Search,Binary,因此,这个方法被传递一个事件的arraylist,每个事件都包含一个字符串和一个频率。频率是这里唯一重要的部分。但我需要做的是使用二进制搜索将arraylist中的最后一个元素插入排序位置。每次运行此代码时,插入位置都打印为-1。我的代码中遗漏了什么吗 我需要跟踪我在二进制搜索过程中遇到的数组中的索引,这应该不会太困难,但解释了返回类型 public ArrayList<Integer> insertLastOccurrence(ArrayList<Occurrence>

因此,这个方法被传递一个事件的arraylist,每个事件都包含一个字符串和一个频率。频率是这里唯一重要的部分。但我需要做的是使用二进制搜索将arraylist中的最后一个元素插入排序位置。每次运行此代码时,插入位置都打印为-1。我的代码中遗漏了什么吗

我需要跟踪我在二进制搜索过程中遇到的数组中的索引,这应该不会太困难,但解释了返回类型

public ArrayList<Integer> insertLastOccurrence(ArrayList<Occurrence> occs) {
    ArrayList<Integer> path = new ArrayList<Integer>();

    int targetFreq = occs.get(occs.size()-1).frequency; //gets the frequency of the thing we want to insert

    //if the array is just 1 value, don't do anything
    if(occs.size() == 1){
        return null;
    }

    int start = 0;               // The start of the search region
    int end = occs.size()-2;// The end of the search region is 1 less than the last position
    int position = -1;           // Position of the target

    // While there is still something list left to search and
    // the element has not been found
    while (start <= end && position == -1)  {
      int mid = start + (end - start) / 2;    //int mid = (start + end) / 2;  // Location of the middle
        // Determine whether the target is smaller than, greater than,
        // or equal to the middle element
        if (targetFreq < occs.get(mid).frequency)   {
        // Target is smaller; continue the left half
        end = mid - 1;
        }
        else if (targetFreq > occs.get(mid).frequency)  {
        // Target is larger, continue the right half
        start = mid + 1;
        }
        else  {
        // Found it!
        position = mid;
        }
    }
    System.out.println(position);   
    return path;
}
公共ArrayList insertLastOccurrence(ArrayList occs){
ArrayList路径=新建ArrayList();
int targetFreq=occs.get(occs.size()-1).frequency;//获取要插入的内容的频率
//如果数组只有1个值,则不要执行任何操作
如果(occs.size()==1){
返回null;
}
int start=0;//搜索区域的开始
int end=occs.size()-2;//搜索区域的结尾比最后一个位置小1
int position=-1;//目标的位置
//但仍有一些列表需要搜索和修改
//未找到该元素
while(启动occs.get(中频){
//目标更大,继续右半部分
开始=中间+1;
}
否则{
//找到了!
位置=中间位置;
}
}
系统输出打印项次(位置);
返回路径;
}

那么,我是否理解这一点?您有一个除最后一个元素(大小为()-1)外已排序的ArrayList,是否要查找此元素必须插入的索引才能重新获得排序属性


我假设,在给出的代码中,只有当ArrayList包含另一个与最后一个(要插入的)元素相等的元素时,才能找到这样的索引,因为只有当targetFreq等于所考虑的元素之一的频率时,位置才设置为中间。由于从未考虑最后一个元素(end=size()-2),很可能找不到相等的元素。

数组是否按频率排序?二进制搜索仅在数组排序时有效,否则继续左/右的假设是错误的。是。除最后一条外的所有条目都已被分类,代码看起来正确。我看不出有什么明显的问题。请转储occs列表并检查订单。也许是降序排序,或者是按字符串排序,而不是按频率排序?哦,我明白你的意思了。因此,我需要修改代码,使其在结束和开始距离为1时停止。这意味着需要在结束和开始之间插入值,对吗?是。可能只要更改while循环的条件并检查是否在循环后设置了位置就足够了。