Skip to content

搞英语 → 看世界

翻译英文优质信息和名人推特

Menu
  • 首页
  • 作者列表
  • 独立博客
  • 专业媒体
  • 名人推特
  • 邮件列表
  • 关于本站
Menu

线性搜索

Posted on 2022-05-30

搜索
在编程中,它是在值列表中找到给定值位置的过程。在我们的日常生活中,它扮演着如此重要的角色,它可以从数据集合中找到一些东西,您可能需要从字典中找到一个单词或从人群中找到您的朋友。

线性/顺序搜索

  • 这是基本的简单搜索算法
  • 在顺序搜索中,我们将目标值与列表中给出的所有其他元素进行比较。例如 arr = {18, 12, 19, 77, 29, 50} (未排序的数组)目标 = 77

在上面的示例中,目标值以顺序/线性方式与数组中的所有元素进行比较。

时间复杂度:

最佳情况:O(1) -> 常数
How many checks will the loop make in the best case ie the element will be found at the 0th index that is only one comparison will be made for best case.

最坏情况:O(n)

 Worst case, here it will go through every element and then it says element not found

图片说明

 public class Main { public static void main(String[] args) { int[] nums = {23, 45, 1, 2, 8, 19, -3, 16, -11, 28}; int target = 19; boolean ans = linearSearch(nums, target); System.out.println(ans); } // search in the array: return the index if item found // otherwise if item not found return -1 static int linearSearch(int[] arr, int target) { if (arr.length == 0) { return -1; } // run a for loop for (int index = 0; index < arr.length; index++) { // check for element at every index if it is = target int element = arr[index]; if (element == target) { return index; } } // this line will execute if none of the return statements above have executed // hence the target not found return -1; } }

有关线性搜索算法的进一步说明,请查看这个精彩的教程
Kunal Kushwaha在 Java 中的线性搜索

请随时在github和Linkedin上与我联系,谢谢。

原文: https://dev.to/rukundob451/linear-search-2ljf

本站文章系自动翻译,站长会周期检查,如果有不当内容,请点此留言,非常感谢。
  • Abhinav
  • Abigail Pain
  • Adam Fortuna
  • Alberto Gallego
  • Alex Wlchan
  • Answer.AI
  • Arne Bahlo
  • Ben Carlson
  • Ben Kuhn
  • Bert Hubert
  • Bits about Money
  • Brian Krebs
  • ByteByteGo
  • Chip Huyen
  • Chips and Cheese
  • Cool Infographics
  • Dan Sinker
  • David Walsh
  • Dmitry Dolzhenko
  • Elad Gil
  • Ellie Huxtable
  • Ethan Marcotte
  • Exponential View
  • FAIL Blog
  • Founder Weekly
  • Geoffrey Huntley
  • Geoffrey Litt
  • Greg Mankiw
  • Henrique Dias
  • Hypercritical
  • IEEE Spectrum
  • Investment Talk
  • Jaz
  • Jeff Geerling
  • Jonas Hietala
  • Josh Comeau
  • Lenny Rachitsky
  • Lou Plummer
  • Luke Wroblewski
  • Matt Stoller
  • Mert Bulan
  • Mostly metrics
  • News Letter
  • NextDraft
  • Non_Interactive
  • Not Boring
  • One Useful Thing
  • Phil Eaton
  • Product Market Fit
  • Readwise
  • ReedyBear
  • Robert Heaton
  • Ruben Schade
  • Sage Economics
  • Sam Altman
  • Sam Rose
  • selfh.st
  • Shtetl-Optimized
  • Simon schreibt
  • Slashdot
  • Small Good Things
  • Taylor Troesh
  • Telegram Blog
  • The Macro Compass
  • The Pomp Letter
  • thesephist
  • Thinking Deep & Wide
  • Tim Kellogg
  • 英文媒体
  • 英文推特
  • 英文独立博客
©2025 搞英语 → 看世界 | Design: Newspaperly WordPress Theme