How Do You Find the Largest and Smallest Numbers in a Python List in O(N^2) Time?

Problem scenario
You want to write a Python program that will accept a list of integers interactively. You want the program to find and print out the largest number and the smallest number of the list entered. You do not want to use the max() or min() functions (which work in Python 3 without importing any library).

What do you do?

Solution

def extremefinder(mainlist):
  a = len(mainlist) - 1
  b = len(mainlist)
  maxnum = 0
  minnum = 0
  for x in mainlist:
    low = 0
    high = 0
    for y in mainlist:
      if (x > y):
          low = low + 1
          if (low == a):  # This never evaluates if x == y. So we use "a" var
            maxnum = x
      else:
          high = high + 1
          if (high == b):   # This handles x == y conditions. So we use "b" var
            minnum = x
  print("The highest number of array provided is on the left below this line")
  print (maxnum, minnum)
  print("The lowest number of array provided is on the right above this line")

print("This program will return the largest and smallest integers from the array provided")
mainlist = list(map(int, input("Please enter a space-separated list of integers: ").rstrip().split()))
extremefinder(mainlist)

Leave a comment

Your email address will not be published. Required fields are marked *