Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม

Linear Search: การค้นหาแบบลำดับ


คืออะไร?

Linear Search (Sequential Search) เทคนิคง่ายที่สุด ค้นหาทีละตัว ใช้ได้กับ Unsorted Data Time Complexity เป็น O(n)

Complexity

  • Time: O(n)
  • Space: O(1)

Input/Output

Input:  20 4 89 75 10 23 45 69  Key: 10
Output: Item found at location: 4

อัลกอริทึม

linearSearch(array, size, key):
  for i = 0 to size-1:
    if array[i] == key: return i
  return invalid

โค้ด C++ และ Output

// linSearch function iterative
// main: input n, array, searchKey
Enter number of items: 8
Enter items: 20 4 89 75 10 23 45 69
Enter search key: 10
Item found at location: 4