【问题标题】:Complexity of the jump search algorithm跳跃搜索算法的复杂性
【发布时间】:2021-08-24 12:52:27
【问题描述】:

我需要一些帮助来计算跳跃搜索算法的复杂度

对不起,它说我需要写更多信息来分享我的问题,所以请忽略这个,我真的需要它。

void jump_search(Pointeur_L1 P, int lenght, char * word) {
Pointeur_L1 inf, max;
max = P;
lenght = longueur_L1(P);
int step = sqrt(lenght);
bool r = false;
int i, j = 0;
while (j < longueur_L1(P)) {
 for (i = 0; i < step; i++) {
   max = max -> suiv;
 }
 if (strcmp(max -> mot, word) == 0) {
   printf("ce mot existe :");
   printf("dans la ligne %d a la position %d \n", max -> line, max -> pos);
   r = true;
 }
 if (strcmp(max -> mot, word) > 0) {
   while (max != NULL) {
     if (strcmp(max -> mot, word) == 0) {
       printf("ce mot existe :");
       printf("dans la ligne %d a la position %d \n", max -> line, max -> pos);
       r = true;
       max = max -> preced;
     } else {
       max = max -> preced;

     }
   }
 } else {
   inf = max;
 }
 j++;
}
if (max == NULL) {
 printf("ce mot n existe pas\n");
}
}

【问题讨论】:

  • 如何计算不同输入大小的复杂性(或分析运行时)以获得第一个想法?
  • 我说我需要帮助来计算复杂性我没有代码错误
  • “我没有代码错误”:代码有错误。尝试使用四个值的列表:2->4->6->8,然后搜索值 9。

标签: c list algorithm function sorting


【解决方案1】:

跳转搜索无法在标准(双)链表中有效实现。跳转搜索的想法是该算法可以在 O(1) 时间内进行一次跳转(√n 步),但这在链表中是不可能的:单次跳转的时间复杂度为 O(√n),因为所有中间必须访问节点。并且在最坏的情况下,必须进行 O(√n) 次跳转,从而访问所有节点,总时间复杂度为 O(n)。

错误和效率低下

您的代码有几个问题:

  • 变量j 使用不正确:如果搜索的值大于列表中的所有数据,那么外部循环肯定会迭代太多次。该外部循环计划迭代列表中的元素的次数,但它最多只能循环 √n 次。只需在没有j 的情况下执行此操作,并将外部循环条件也设为:max != NULL,就像内部循环一样。

  • 还应保护for 循环免受空指针异常的影响。在for 循环的条件中包含max != NULL

    for (i = 0; i < step && max != NULL; i++) {
         max = max -> suiv;
    }
    
  • 如果搜索到的单词不在列表中,则内循环:

    while (max != NULL) {
    
    }
    

    ...将返回列表一直到列表的开头。这是浪费时间;当节点中的值小于搜索值时,它应该停止向后看:

    while (max != NULL) {
        int result = strcmp(max -> mot, word);
        if (result == 0) {
            printf("ce mot existe :");
            printf("dans la ligne %d a la position %d \n", max -> line, max -> pos);
            return;
        }
        if (result < 0) {
            break;
        } 
        max = max -> preced;
    }
    printf("ce mot n existe pas\n");
    return;
    
  • 您有变量 infr 没有任何用处。

  • 如果函数能返回一些东西,它会更有用。它可以是一个布尔值,也可以是找到的节点(如果没有找到,则为 null)。

  • 不要在这个函数中打印结果。在同一个函数中混合 I/O 和逻辑并不是一个好习惯。打印是主程序应该做的事情,而不是这样的功能。如果你让函数返回找到的节点(或null),那么调用者可以使用该信息来产生你需要的输出。

跳转搜索比较

有一点,这种跳转搜索仍然比链表中的普通线性搜索做得更好:它不会对其 forward 中的每个元素执行 比较搜索。跳转搜索比较的次数是O(√n)。如果对它进行了上述更正,则在此实现中也是如此。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-07-16
    • 1970-01-01
    • 2012-08-19
    • 2019-05-05
    • 1970-01-01
    • 2012-03-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多