Advertisement
scarygarey

linear_binary_compared

Jan 14th, 2020
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.33 KB | None | 0 0
  1. #-------------------------------------------------------------------------------
  2. # Name: module1
  3. # Purpose:
  4. #
  5. # Author: dgarey
  6. #
  7. # Created: 14/01/2020
  8. # Copyright: (c) dgarey 2020
  9. # Licence: <your licence>
  10. #-------------------------------------------------------------------------------
  11. from timeit import timeit
  12. from random import randint
  13.  
  14. list_to_search = [i for i in range(1000000)]
  15. #linear search
  16. def linear_search (listnums,search):
  17. import random
  18. listnums = []
  19. for i in range(0,50): #will populate 50 random numbers
  20. listnums.append(random.randint(0,100)) # will select 50 random numbers between 1-100)
  21. listnums.sort()
  22. print (listnums) #the numbers randomly selected will appear below
  23.  
  24. print("what integer are you searching for between 1-100?")
  25. search = int(input()) #requires user to input a number
  26.  
  27. found = False
  28.  
  29. for i in range (0,len(listnums)): # this checks from the first position in the random number list
  30. if listnums[i] == search: #if number entered is found in the list
  31. found = True
  32.  
  33. if found == True:
  34. print("this integer is in the list") #foundl
  35. else:
  36. print("this integer is not in the list") #not found
  37.  
  38. #Binary Search
  39. def binary_search(listnums,search):
  40. found = False
  41. left = 0
  42. right = len(listnums)-1
  43. while left!=right:
  44. midpoint = (left + right)//2
  45. if listnums[midpoint] == search:
  46. found = True
  47. break
  48. if search <= listnums[midpoint]:
  49. right = midpoint
  50. else:
  51. left = midpoint+1
  52. return found,midpoint
  53.  
  54. import random
  55. listnums = []
  56. for i in range(0,50): #will populate 50 random numbers
  57. listnums.append(random.randint(0,100)) # will select 50 random numbers between 1-100)
  58. listnums.sort()
  59. print(listnums) #the numbers randomly selected will appear below
  60.  
  61. print("what integer are you searching for between 1-100?")
  62. search = int(input()) #requires user to input a number
  63.  
  64. found,midpoint = binary_search(listnums,search)
  65. print(found)
  66. print(midpoint+1)
  67.  
  68. ls = lambda: linear_search(list_to_search, randint(0,1000000))
  69. bs = lambda: binary_search(list_to_search, randint(0,1000000))
  70.  
  71. #time the functions for 100 runs each
  72. print("Linear search took:")
  73. print(timeit(ls, number = 100))
  74.  
  75. print("Binary search took:")
  76. print(timeit(bs, number = 100))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement