Topics in this subject
NumPy 1 min read Updated 4 Aug 2026

10. Sorting & Searching

a = np.array([3, 1, 2])

a = np.array([3, 1, 2])
np.sort(a)             # [1 2 3]  (returns sorted copy)
a.argsort()            # [1 2 0]  (indices that would sort a)
a.argmax(), a.argmin() # 0, 1     (index of max / min)

b = np.array([1, 3, 5, 7])
np.searchsorted(b, 4)  # 2  (insert index to keep sorted)

x = np.array([-2, 0, 3, -1, 5])
np.where(x > 0, x, 0)  # [0 0 3 0 5]   (vectorized if/else)
np.nonzero(x)          # (array([0, 2, 3, 4]),)  indices of nonzeros
np.extract(x > 0, x)   # [3 5]

u, counts = np.unique(np.array([1,1,2,3,3,3]), return_counts=True)
# u=[1 2 3], counts=[2 1 3]
np.bincount(np.array([0,1,1,2,2,2]))   # [1 2 3]  count of each value
np.histogram(np.array([1,2,1,3]), bins=3)
Function Returns
sort sorted copy (use .sort() for in-place)
argsort indices that sort the array
argmax/argmin index of extreme value
searchsorted insertion index into a sorted array (binary search, O(log n))
where(cond, x, y) element-wise choose
nonzero indices of nonzero elements
unique sorted unique values (optionally counts)
bincount count of each non-negative integer

Interview Question: How to get top-k elements efficiently? np.argpartition(a, -k)[-k:] runs in O(n) vs argsort's O(n log n).

💡 Tip: np.where(cond) with one argument returns indices; with three arguments it's a ternary.