python算法系列排序与查找_NumPy排序和搜索算法示例

Numpy提供了多种用于排序和搜索的功能。有多种排序算法, 例如quicksort, merge sort和heapsort, 是使用numpy.sort()函数实现的。

必须在函数调用中提及排序操作中使用的排序算法的种类。

让我们讨论在numpy.sort()中实现的排序算法

SN

Algorithm

最坏情况下的复杂性

1

Quick Sort

O(n ^ 2)

2

Merge Sort

O(n * log(n))

3

堆排序

O(n * log(n))

下面给出了使用numpy.sort()函数的语法。

numpy.sort(a, axis, kind, order)

它接受以下参数。

SN

Parameter

Description

1

input

它表示要排序的输入数组。

2

axis

它表示要对数组进行排序的轴。如果未提及轴, 则沿最后一个可用轴进行排序。

3

kind

它表示排序时要使用的排序算法的类型。默认为快速排序。

4

order

如果数组包含字段, 它表示要对数组进行排序的字段。

考虑以下示例。

例子

import numpy as np

a = np.array([[10, 2, 3], [4, 5, 6], [7, 8, 9]])

print("Sorting along the columns:")

print(np.sort(a))

print("Sorting along the rows:")

print(np.sort(a, 0))

data_type = np.dtype([('name', 'S10'), ('marks', int)])

arr = np.array([('Mukesh', 200), ('John', 251)], dtype = data_type)

print("Sorting data ordered by name")

print(np.sort(arr, order = 'name'))

输出

Sorting along the columns:

[[ 2 3 10]

[ 4 5 6]

[ 7 8 9]]

Sorting along the rows:

[[ 4 2 3]

[ 7 5 6]

[10 8 9]]

Sorting data ordered by name

[(b'John', 251) (b'Mukesh', 200)]

numpy.argsort()函数

此函数用于对输入数组执行间接排序, 即, 它返回数据索引数组, 该索引用于构造已排序数据数组。

考虑以下示例。

例子

import numpy as np

a = np.array([90, 29, 89, 12])

print("Original array:\n", a)

sort_ind = np.argsort(a)

print("Printing indices of sorted data\n", sort_ind)

sort_a = a[sort_ind]

print("printing sorted array")

for i in sort_ind:

print(a[i], end = " ")

输出

Original array:

[90 29 89 12]

Printing indices of sorted data

[3 1 2 0]

printing sorted array

12 29 89 90

numpy.lexsort()函数

此函数用于间接使用键序列对数组进行排序。该函数的执行类似于numpy.argsort(), 该函数返回已排序数据的索引数组。

考虑以下示例。

例子

import numpy as np

a = np.array(['a', 'b', 'c', 'd', 'e'])

b = np.array([12, 90, 380, 12, 211])

ind = np.lexsort((a, b))

print("printing indices of sorted data")

print(ind)

print("using the indices to sort the array")

for i in ind:

print(a[i], b[i])

输出

printing indices of sorted data

[0 3 1 4 2]

using the indices to sort the array

a 12

d 12

b 90

e 211

c 380

numpy.nonzero()函数

此函数用于从数组中查找非零元素的位置。

考虑以下示例。

例子

import numpy as np

b = np.array([12, 90, 380, 12, 211])

print("printing original array", b)

print("printing location of the non-zero elements")

print(b.nonzero())

输出

printing original array [ 12 90 380 12 211]

printing location of the non-zero elements

(array([0, 1, 2, 3, 4]), )

numpy.where()函数

此函数用于返回满足特定条件的所有元素的索引。

考虑以下示例。

例子

import numpy as np

b = np.array([12, 90, 380, 12, 211])

print(np.where(b>12))

c = np.array([[20, 24], [21, 23]])

print(np.where(c>20))

输出

(array([1, 2, 4]), )

(array([0, 1, 1]), array([1, 0, 1]))

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值