This Saturday class we went over indexing and ordering a group of items by their sorted indices. For those who are more advanced, please go over the section on quick sort.

For example,

>> import numpy as np

>>> packpack =np.array([‘snack’,’book’,’pen’,’eraser’,’apple’])

# Position of the biggest word (alphabetically)

`>>> np.argmax(packpack)`

[out]: 0

# Position of the smallest word (alphabetically)

`>>> np.argmin(packpack)`

[out]: 4

# Position of the words if we are to sort them alphabetically

`>>> np.argsort(packpack)`

[out]: array([4, 1, 3, 2, 0], dtype=int64)

Now let us sort them:

`>>> packpack[np.argsort(packpack)]`

[out]: array([‘apple’, ‘book’, ‘eraser’, ‘pen’, ‘snack’], dtype='<U6′)

Then we tried sorting numbers:

numbers = np.array([2,3,5,7,1,4,6,15,5,2,7,9,10,15,9,17,12])

`>>> numbers[np.argsort(numbers)]`

[out]: array([ 1, 2, 2, 3, 4, 5, 5, 6, 7, 7, 9, 9, 10, 12, 15, 15, 17])

Finally we dig deeper: how do you really sort things fast systematically? Using quick sort!

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
def quick_sort(data): """快速排序""" if len(data) >= 2: # 递归入口及出口 mid = data[len(data)//2] # 选取基准值，也可以选取第一个或最后一个元素 left, right = [], [] # 定义基准值左右两侧的列表 data.remove(mid) # 从原始数组中移除基准值 for num in data: if num >= mid: right.append(num) else: left.append(num) return quick_sort(left) + [mid] + quick_sort(right) else: return data numbers= [2,3,5,7,1,4,6,15,5,2,7,9,10,15,9,17,12] Backpack = ['snack','book','pen','eraser','apple'] print(quick_sort(Backpack)) print(quick_sort(numbers)) |