When we talk about running time, we are talking about time as a function of the number of items in the list. The simplest way running time can be reduced is by limiting the number of helper function calls. The example we were shown was using a variable or for loop instead of a while loop if we are going through the whole list.
len(n) is called n times, this is an extremely large amount of calls
i = 0
while i != len(n):
(search stuff)
i += 1
len(n) is called only once but n comparisons are made. The comparison is another helper function so this could still be refined.
i = 0
length = len(n)
while i != length:
(search stuff)
i += 1
len(n) is only called once in this code and no comparisons need to be made. We saved 2n function calls by using a for loop which is significant for large lists.
for i in len(n):
(search stuff)
While these save time, the biggest difference in running time will actually be in the algorithm. This is because the fastest unordered list sorting algorithms run with O(n*logn) running time which grows faster than that 2n we saved.
Below are example algorithms we covered in lab and their running time.
Example Algorithms:
Bubble sort: O(n²) running time.
Selection sort: O(n²) running time.
Insertion sort: O(n²) running time.
Merge sort: O(n*logn) running time.
Quick sort: O(n*logn) running time.
Python inbuilt (Tim sort): O(n*logn) running time.
No comments:
Post a Comment