# 数组的排序 - 数组排序默认使用快排 - 根据选择,可以选用其他方式排序 - 可选参数还有axis,可以选择沿着哪个方向排序,此时把这个方向的数据当初独立数组对待 ## sort - 默认快排, 其他归并排序,堆排序, 稳定排序 - 不修改源数据,返回排好的数据下使用np.sort(data) - 修改数据源,使用 data.sort() ```python x = np.random.randint(20, size =10) print("排序前 X = ", x) a = np.sort(x) print("排序后 X = ", x) print("排序后 a = ", a) x.sort() print("修改数据源排序后 X = ", x) ``` 排序前 X = [ 3 8 5 7 17 0 16 16 1 8] 排序后 X = [ 3 8 5 7 17 0 16 16 1 8] 排序后 a = [ 0 1 3 5 7 8 8 16 16 17] 修改数据源排序后 X = [ 0 1 3 5 7 8 8 16 16 17] ## argsort - 返回排序后数据的索引 ```python x = np.random.randint(20, size =10) print("排序前 X = ", x) a = np.argsort(x) print("排序后的索引: ", a) ``` 排序前 X = [10 2 0 6 10 3 9 2 18 8] 排序后的索引: [2 1 7 5 3 9 6 0 4 8] ## 分隔 - 选择出前k个最小的值,以排序第k个值为界限,小于它的在前面,等于大于它的在后面 - 选择结果在数组左侧,其余的在数组右侧 - 两侧排序不规则 - 使用方法是 np.partition(x, k) ```python x = np.random.randint(100, size=10) print("排序前 x= ", x) a = np.partition(x, 4) print("分隔后的值 x= ", a) ``` 排序前 x= [99 71 55 60 86 16 18 51 53 37] 分隔后的值 x= [16 51 18 37 53 71 55 60 86 99] ```python x = np.random.randint(100, size=(4,5)) print("排序前 x = \n", x) a = np.partition(x, 3, axis=1) print("沿着axis=1分隔后的数据是 \n", a) ``` 排序前 x = [[33 16 2 12 51] [28 61 55 95 18] [30 23 72 57 89] [20 49 23 26 0]] 沿着axis=1分隔后的数据是 [[12 2 16 33 51] [18 28 55 61 95] [57 30 23 72 89] [ 0 20 23 26 49]]