Computer >> คอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

โปรแกรม Python สำหรับการค้นหาเชิงเส้น


ในบทความนี้ เราจะเรียนรู้เกี่ยวกับการค้นหาเชิงเส้นและการนำไปใช้ใน Python 3.x หรือก่อนหน้านั้น

อัลกอริทึม

Start from the leftmost element of given arr[] and one by one compare element x with each element of arr[]
If x matches with any of the element, return the index value.
If x doesn’t match with any of elements in arr[] , return -1 or element not found.

ตอนนี้เรามาดูการแสดงภาพของวิธีการที่กำหนด -

โปรแกรม Python สำหรับการค้นหาเชิงเส้น

ตัวอย่าง

def linearsearch(arr, x):
   for i in range(len(arr)):
      if arr[i] == x:
         return i
      return -1
arr = ['t','u','t','o','r','i','a','l']
x = 'a'
print("element found at index "+str(linearsearch(arr,x)))

ผลลัพธ์

element found at index 6

ขอบเขตของตัวแปรแสดงอยู่ในรูป -

โปรแกรม Python สำหรับการค้นหาเชิงเส้น

บทสรุป

ในบทความนี้ เราได้เรียนรู้เกี่ยวกับกลไกการค้นหาเชิงเส้นใน Python3.x หรือก่อนหน้านั้น