MidYouth
讲师:李浩然
求 498 * 9 的结果
- 498 * 9 = 3600 + 810 + 72 = 4482
- 498 * 9 = 500 * 9 - 2 * 9 = 4482
不同的算法有着不同的效率,但是完成的任务是相同的。
ls = [ 81, 94, 92, 71, 98, 87 ]
max = ls[0]
for i in range( 1, len(ls) ):
if ls[i] > max:
max = ls[i]
找出如下列表中的最小值:
>>> ls = [ 81, 94, 92, 71, 98, 87 ]
求如下列表所有项的和:
>>> ls = [ 81, 94, 92, 71, 98, 87 ]
如果你有认真听我讲的第五期课程:数据结构,你应该知道以上三个问题都可以分别用一个方法实现。在这里还是希望大家能够将这几个题的算法写出来,从而对算法更加熟悉。
ls = [30, 50, 10, 20, 40]
n = len(ls)
for i in range(n):
for j in range(0, n-i-1):
if ls[j] > ls[j + 1]:
ls[j], ls[j + 1] = ls[j + 1], ls[j] # 两项互换位置
# 在以上的代码中,最后一行代码也可以用另外一种更为常见的方式实现。
temp = ls[j]
ls[j] = ls[i]
ls[i] = temp
# 他们本质上并没有什么区别,只是写法不同而已。
ls = [30, 50, 10, 20, 40]
n = len(ls)
for i in range(n):
index_of_min = i
for j in range(i + 1, n):
if ls[j] < ls[index_of_min]:
index_of_min = j
ls[i], ls[index_of_min] = ls[index_of_min], ls[i]
O(n)
来表示。6+5+4+3+2+1 = 21
次。
(n - 1) + (n - 2) + (n - 3) + ... + 3 + 2 + 1
= (n - 1 + 1) + (n - 2 + 2) + (n - 3 + 3) + ... + (n - n + n)
= (n - 1) * n / 2
O(n) = n^2 / 2
6+5+4+3+2+1 = 21
次。
(n - 1) + (n - 2) + (n - 3) + ... + 3 + 2 + 1
= (n - 1 + 1) + (n - 2 + 2) + (n - 3 + 3) + ... + (n - n + n)
= (n - 1) * n / 2
O(n) = n^2 / 2
排序算法 | 时间复杂度 |
---|---|
冒泡排序 | O(n^2) |
选择排序 | O(n^2) |
...... | ...... |
归并排序 | O(n*logn) |
插入排序 | O(n^2) |
希尔排序 | O(n^1.25) |
ls = [ 10, 20, 30, 40, 50, 60, 70 ]
# 查找数字 50
index = -1
for i in range(len(ls)):
if ls[i] == 50:
index = i # 数字 50 在索引 index 上
ls = [10, 20, 30, 40, 50, 60, 70]
low_index = 0
high_index = len(ls) - 1
middle_index = int((low_index + high_index) / 2)
while low_index < high_index:
if ls[middle_index] > 50:
high_index = middle_index - 1
middle_index = int((low_index + high_index)/2)
elif ls[middle_index] < 50:
low_index = middle_index + 1
middle_index = int((low_index + high_index)/2)
else:
break
middle_index # 4
在这个作业中,我将会给大家提供一个 python 文件,开头是三个长度为一万的列表,格式分别为正序、倒序和随机。请大家写出来一个程序,将这三个列表分别用冒泡排序算法(请写出来)、选择排序算法(请写出来)和归并排序算法(代码会提供)排序,并记录程序运行的时间。
请大家将自己写的代码以及代码的运行结果发给我,然后对结果进行分析。想怎么分析就怎么分析,但是我会打分的哦~