Q小姐的學習筆記
Q小姐的學習筆記

Hello World ! 我是Q小姐NaNa,會在這裡分享學習筆記,歡迎交流討論🙆

演算法學習筆記-線性搜尋(Linear Search)

線性搜尋法(Linear Search)又稱順序搜尋法(Sequential Search),是將數組中元素從第一個開始依序與搜尋目標值比對,直到找到為止。

方法分析

線性搜尋法不需先將陣列中的n個元素依序排列(如由小到大排列),但因為都是從頭開始搜尋,最佳情況是第一個元素就是目標值,但若是目標值在最後一個,就需要進行n次比較。

方法實踐

以在整數23、90 、38、 15、 49、 76、 54中搜尋76為例,實踐如下:

  • 將23、90 、38、 15、 49、 76、 54放入整數陣列array中。
  • 從陣列最左邊的元素開始,將目標值76與數組中每個索引值的元素逐一比較。
  • 當目標值匹配數組中索引值的元素,即返回索引值並結束搜尋。
  • 當搜尋到數組最右邊元素,仍沒有找到目標值,表示目標值未存在此數組中。
以Java實踐
以Java實踐
class test {
  // Driver code
  public static void main(String[] args) {
    int[] array = {23, 90, 38, 15, 49, 76, 54};
    int key = 76;

    // Function call
    int result = linearSearch(array, key);
    if (result == -1) {
      System.out.println("The key number " + key + " is not present in array");
    } else {
      System.out.println("The key number " + key + " is present at index " + result);
    }
  }

  // Linear Search
  public static int linearSearch(int[] array, int num) {
    for (int index = 0; index < array.length; index++) {
      if (num == array[index]) {
        return index;
      }
    }
    return -1;
  }
}

共同作者:https://matters.news/@CHWang

CC BY-NC-ND 2.0 版权声明

喜欢我的文章吗?
别忘了给点支持与赞赏,让我知道创作的路上有你陪伴。

加载中…

发布评论