Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/http/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Algorithm 排序数组中K的秩的求法_Algorithm_Sorting_Data Structures - Fatal编程技术网

Algorithm 排序数组中K的秩的求法

Algorithm 排序数组中K的秩的求法,algorithm,sorting,data-structures,Algorithm,Sorting,Data Structures,这是一道练习题。我不想给你一个完整的答案,但任何提示或改进都将不胜感激 搜索问题是,给定(A,K),其中A被排序,找到A中K的秩,也就是说,找出A中有多少元素小于K。假设A已经加载到内存中(所以你不计算读取A的时间-可能是因为你要在A中进行大量搜索,所以你只需要读取一次) 给出一个算法来解决搜索问题,并找到解决这个问题的任何算法的下界,假设k只能与A的元素进行比较 到目前为止我所拥有的。 由于数组是经过排序的,并且由于没有给出数组的大小n,所以我们不知道数组的大小n,因此我们没有使用二进制搜索的

这是一道练习题。我不想给你一个完整的答案,但任何提示或改进都将不胜感激

搜索问题是,给定(A,K),其中A被排序,找到A中K的秩,也就是说,找出A中有多少元素小于K。假设A已经加载到内存中(所以你不计算读取A的时间-可能是因为你要在A中进行大量搜索,所以你只需要读取一次)

给出一个算法来解决搜索问题,并找到解决这个问题的任何算法的下界,假设k只能与A的元素进行比较

到目前为止我所拥有的。 由于数组是经过排序的,并且由于没有给出数组的大小n,所以我们不知道数组的大小n,因此我们没有使用二进制搜索的适当界限。所以为了找到钥匙的位置

first we find bounds and then apply binary search algorithm.  

Let low be pointing to 1st element and high pointing to 2nd element of array, Now compare key with high index element,

->if it is greater than high index element then copy high index in low index and double the high index.

->if it is smaller, then apply binary search on high and low indices found.

And since we are using binary search the complexity will be lon(n).
有人能告诉我这是不是正确的,或者给出一个关于如何继续解决这个问题的提示。谢谢

私有整数排名(整数低、整数高、整数[]项、整数元素){
 private int rank(int lo, int hi, int[] items, int element) {
    int mid = 0;
    int highestRank = hi;
    while (lo <= hi) {
        mid = lo + (hi - lo) / 2;
        if (element < items[mid]) {
            hi = mid - 1;
        } else if (element > items[mid]) {
            lo = mid + 1;
        } else {
            return highestRank + 1 - mid;
        }

    }
    int elementPosition = hi;
    int rank;
    if (elementPosition > highestRank) {
        rank = 1;
    } else if (elementPosition < 0) {
        rank = highestRank + 1 + 1;
    } else {
        rank = highestRank + 1 - elementPosition;
    }
    return rank;
}
int-mid=0; int highestRank=hi; while(低项[中]){ lo=中间+1; }否则{ 返回highestRank+1-mid; } } int elementPosition=hi; 整数秩; 如果(元素位置>高位链接){ 秩=1; }else if(元素位置<0){ 秩=高位链节+1+1; }否则{ 排名=高位链接+1-元素位置; } 返回等级; }

如果对items数组进行了排序,并且不应该有任何重复项,则此方法有效。

如果没有给出边界,您如何查找边界?如果您只是在数组中进行迭代,那么之后就不需要使用二进制搜索,您可以在迭代时找到答案。如果使用数组,您通常假定知道数组的大小。否则,您如何知道数组的结束位置?