0

I am not sure on how to time a bubble sort like this, any input is appreciated! In addition i'd like to be able to 'print' how long it took in seconds after sorting. Also any comments on the code itself are welcome!

    def bubbleSort(list):
        needNextPass = True

        k = 1
        while k < len(list) and needNextPass:
            # List may be sorted and next pass not needed
            needNextPass = False
            for i in range(len(list) - k): 
                if list[i] > list[i + 1]:
                    # swap list[i] with list[i + 1]
                    temp = list[i]
                    list[i] = list[i + 1]
                    list[i + 1] = temp

                    needNextPass = True # Next pass still needed

    # A test method 
    def main():
        list = [5000, 200000, 250000, 10000, 150000, 300000]
        bubbleSort(list)
        for v in list:
            print("Bubble sort list: ",v, end = ",")




    main()
  • you can use `%timeit` – Julien Apr 30 '18 at 00:47
  • Simplest form is perf_counter() as: `start = time.perf_counter()` `function(x)` and `end = time.perf_counter()` `end - start` is the time it took. – What Apr 30 '18 at 00:48
  • Possible duplicate of [Measure time elapsed in Python?](https://stackoverflow.com/questions/7370801/measure-time-elapsed-in-python) – eesiraed Apr 30 '18 at 01:12

1 Answers1

1
import time

def bubble_sort(list):

  # Implementation of bubble sort

  return list

#------------------------------------

def main():

  l = [1,5,7,6,8]

  start_time = time.time()

  bubble_sort(l)

  stop_time = time.time()

  duration = stop_time - start_time()

#------------------------------------

main()