【问题标题】:Array search code数组搜索代码
【发布时间】:2013-02-19 11:56:50
【问题描述】:

在《Java 中的数据结构和算法》一书中,提供了以下数组搜索方法代码:

{
    int j;
    for(j=0; j< nElems; j++)            // for each element,
        if( a[j].getLast().equals(searchName))  // found item?
             break;                       // exit loop before end
    if(j == nElems)                    // gone to end?
      return null;                    // yes, can't find it
    else
      return a[j];                    // no, found it
} 

我想了解为什么需要进行 if(j == nElems) 检查?如果写成这样,该方法的工作方式会不会相同:

{           
    int j;
    for(j=0; j <nElems; j++)               
      if( a[j].getLast().equals(searchName))      
         return a[j];              
    return null;
}

【问题讨论】:

  • 如果格式正确,您可以更好地理解代码。

标签: java arrays search


【解决方案1】:

它会 :P 您也可以在 for 中声明 j 以限制其范围。

在第一个实现中,它所做的是检查它是否遍历了所有元素并且没有找到任何东西,因为j 被递增直到它等于for-loop 的停止条件。即它没有因为break而停止,说明它找到了一个元素。

我更喜欢你的解决方案,因为它更容易阅读:)

【讨论】:

    【解决方案2】:

    是的,这两种方式的结果都是一样的。

    【讨论】:

      【解决方案3】:

      好吧,j 永远不等于 nElems,所以这个条件 (j==nElems) 没有错,但它不起作用。 你可以像这样(j==nElems-1) 但它是偷代码的浪费,所以你的算法比第一个更好。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-10-12
        • 2018-09-18
        • 2018-09-20
        • 1970-01-01
        • 2016-05-26
        相关资源
        最近更新 更多