Notification texts go here Contact Us Click here

Searching techniques in python

Please wait 0 seconds...
Scroll Down and click on Go to Link for destination
Congrats! Link is Generated
  1. 1Program of  Linear searching using python.
  2.  
  3. def linear_search(arr, target):
  4.     for i in range(len(arr)):
  5.         if arr[i] == target:
  6.             return i  # Return the index of the target if found
  7.     return -1         # Return -1 if the target is not found
  8.  
  9. my_list = input("Enter the n elements: ")
  10. target_value = input("Enter the elements to be searching in list: ")
  11.  
  12. result = linear_search(my_list, target_value)
  13.  
  14. if result != -1:
  15.     print(f"Target value {target_value} found at index {result}")
  16. else:
  17.     print(f"Target value {target_value} not found in the list")
  18.  
  19.  
  20. OUTPUT :
  21.  
  22.         Enter the n elements: 1 2 3 4 23 34 45 56 67 78 89 90
  23.         Enter the elements to be searching in list2
  24.         Target value 2 found at index 2
  25.  
  26. 2Program of Binary Searching using python .
  27.  
  28. def binary_search(arr, target):
  29.     low = 0
  30.     high = len(arr) - 1
  31.  
  32.     while low <= high:
  33.         mid = (low + high) // 2
  34.         mid_value = arr[mid]
  35.  
  36.         if mid_value == target:
  37.             return mid  # Return the index of the target if found
  38.         elif mid_value < target:
  39.             low = mid + 1
  40.         else:
  41.             high = mid - 1
  42.  
  43.     return -1  # Return -1 if the target is not found
  44.  
  45. # Example usage
  46. my_list = [1, 2, 3, 4, 5, 8, 9, 10, 12, 16]   #user create own list.
  47. target_value = 8                              #search user desire elements
  48.  
  49. result = binary_search(my_list, target_value)
  50.  
  51. if result != -1:
  52.     print(f"Target value {target_value} found at index {result}")
  53. else:
  54.     print(f"Target value {target_value} not found in the list")
  55.  
  56. OUTPUT:
  57.        Target value 8 found at index 5

Post a Comment

Cookie Consent
We serve cookies on this site to analyze traffic, remember your preferences, and optimize your experience.
Oops!
It seems there is something wrong with your internet connection. Please connect to the internet and start browsing again.
AdBlock Detected!
We have detected that you are using adblocking plugin in your browser.
The revenue we earn by the advertisements is used to manage this website, we request you to whitelist our website in your adblocking plugin.