DEV Community

Cover image for Linear, Random or Binary Search
Medea
Medea

Posted on

Linear, Random or Binary Search

For school, we had an assignment in Python where we had to use Linear, Random or Binary Search with a number game.


Linear Search

Linear search is when each item in the list is examined one at a time from the beginning.
An example of linear search code is below:

number = random.randint(1,100)
count = 0
for i in range(1,100):
  count = count + 1
  if i == number:
    print("The number was " + str(number))
    print("You got it in " + str(count) + " guesses!")
    break
Enter fullscreen mode Exit fullscreen mode

Random Search

Random search is where each item in the list is selected randomly and checked until the correct item is found.
An example of random search code is below:

number = random.randint(1,100)
allnum = []
for i in range(1,100):
  allnum.append(i)
guess = random.choice(allnum)
allnum.remove(guess)
count = 1
while guess != number:
  count = count + 1
  guess = random.choice(allnum)
  allnum.remove(guess)
print("The number was " + str(number))
print("You got it in " + str(count) + " guesses!")
Enter fullscreen mode Exit fullscreen mode

Binary Search

Binary search is when you cut through the list by halving each time, until you find the number you are looking for.

number = random.randint(1,100)
lowestnumber = 1
highestnumber = 100
guess = round((highestnumber + lowestnumber) / 2)
count = 1
while guess != number:
  if guess > number:
    if highestnumber > guess:
      highestnumber = guess
    print("The number is smaller than " + str(guess))
  if guess < number:
    if guess > lowestnumber:
      lowestnumber = guess
    print("The number is bigger than " + str(guess))
  guess = guess = round((highestnumber + lowestnumber) / 2)
  count = count + 1
print("The number was " + str(number))
print("You got it in " + str(count) + " guesses!")
Enter fullscreen mode Exit fullscreen mode

Which searching do you think is the most efficient?

Discussion (0)