NumPy: Sorting and Searching
Last updated: 2026-08-26
1. What You'll Learn
- ❶
np.sort— sorting arrays along any axis - ❷
np.argsort— getting the indices that would sort - ❸
np.searchsorted— finding insertion positions in sorted arrays - ❹
np.unique— finding unique elements - ❺
np.partition— partial sorting for top-k
2. Key Concepts
(1) Sorting
PYTHON
import numpy as np
a = np.array([3, 1, 4, 1, 5, 9, 2, 6])
print(np.sort(a)) # [1 1 2 3 4 5 6 9]
print(np.argsort(a)) # [1 3 0 6 2 4 7 5] (indices)
# 2D sorting
b = np.array([[3, 1, 4],
[1, 5, 9]])
print(np.sort(b, axis=0)) # sort each column
print(np.sort(b, axis=1)) # sort each row
TEXT
📖 Display only
> **Output:** Run NumPy 2.x in your local Python environment to see the ndarray output. The Piston server does not have NumPy pre-installed — install it locally (`pip install numpy`) and compare. Actual values may vary by NumPy version and random seed.
(2) Searching
PYTHON
import numpy as np
a = np.array([1, 3, 5, 7, 9])
# Find insertion positions (array must be sorted)
print(np.searchsorted(a, 4)) # 2 (insert between 3 and 5)
print(np.searchsorted(a, [2, 6, 8])) # [1 3 4]
# Find indices where condition is True
print(np.where(a > 4)) # (array([2, 3, 4]),)
TEXT
📖 Display only
> **Output:** Run NumPy 2.x in your local Python environment to see the ndarray output. The Piston server does not have NumPy pre-installed — install it locally (`pip install numpy`) and compare. Actual values may vary by NumPy version and random seed.
(3) Unique
PYTHON
a = np.array([3, 1, 4, 1, 5, 9, 2, 6, 5, 3])
print(np.unique(a)) # [1 2 3 4 5 6 9]
# With counts
vals, counts = np.unique(a, return_counts=True)
print(vals) # [1 2 3 4 5 6 9]
print(counts) # [2 1 2 1 2 1 1]
TEXT
📖 Display only
> **Output:** Run NumPy 2.x in your local Python environment to see the ndarray output. The Piston server does not have NumPy pre-installed — install it locally (`pip install numpy`) and compare. Actual values may vary by NumPy version and random seed.
▶ Example: Sorting arrays (Difficulty ⭐)
PYTHON
import numpy as np
a = np.array([3, 1, 4, 1, 5, 9, 2, 6])
# Sort returns a sorted copy
sorted_a = np.sort(a)
print("Original:", a)
print("Sorted:", sorted_a)
# In-place sort
a.sort()
print("In-place:", a)
# 2D sort along axis
b = np.array([[3, 1, 4], [1, 5, 9]])
print("Sort columns:\n", np.sort(b, axis=0))
print("Sort rows:\n", np.sort(b, axis=1))
Output:
TEXT 📖 Display onlyOriginal: [3 1 4 1 5 9 2 6] Sorted: [1 1 2 3 4 5 6 9] In-place: [1 1 2 3 4 5 6 9] Sort columns: [[1 1 4] [3 5 9]] Sort rows: [[1 3 4] [1 5 9]]
▶ Example: Using argsort (Difficulty ⭐⭐)
PYTHON
import numpy as np
scores = np.array([85, 92, 78, 95, 88])
names = np.array(['Alice', 'Bob', 'Charlie', 'Diana', 'Eve'])
# Get indices that would sort scores
idx = np.argsort(scores)
print("Indices:", idx)
print("Sorted scores:", scores[idx])
# Sort names by their scores (descending)
desc_idx = np.argsort(-scores)
print("Ranking:")
for rank, i in enumerate(desc_idx, 1):
print(f" {rank}. {names[i]}: {scores[i]}")
Output:
TEXT 📖 Display onlyIndices: [2 0 4 1 3] Sorted scores: [78 85 88 92 95] Ranking: 1. Diana: 95 2. Bob: 92 3. Eve: 88 4. Alice: 85 5. Charlie: 78
▶ Example: Finding unique values with counts (Difficulty ⭐)
PYTHON
import numpy as np
grades = np.array(['A', 'B', 'A', 'C', 'B', 'A', 'B', 'B', 'C', 'A'])
unique, counts = np.unique(grades, return_counts=True)
print("Grades:", unique)
print("Counts:", counts)
# Find where to insert values into a sorted array
sorted_arr = np.array([1, 3, 5, 7, 9])
pos = np.searchsorted(sorted_arr, [2, 4, 6, 8])
print("Insertion positions:", pos)
Output:
TEXT 📖 Display onlyGrades: ['A' 'B' 'C'] Counts: [4 4 2] Insertion positions: [1 2 3 4]
Q Does
np.sort modify the original array?A No — it returns a sorted copy. Use
a.sort() (in-place method) to sort the original array without creating a copy.Q What's the difference between
np.sort and np.argsort?A
np.sort returns the sorted values. np.argsort returns the indices that would produce the sorted array. Use argsort when you need to sort multiple arrays by the same order.Q What is
np.partition?A It partially sorts the array so that the k-th smallest element is in its final position, with smaller elements before it and larger elements after (in arbitrary order). Faster than full sort for top-k queries.
❓ FAQ
Q What is the most important thing to remember?
A NumPy operations are vectorized — avoid Python loops for better performance.
Q Where can I learn more?
A Check the official NumPy documentation at numpy.org for detailed references and advanced topics.
Q Does this work with NumPy 2.x?
A Yes — all examples are compatible with NumPy 2.x. Some older APIs (like np.random.seed) are still supported but the modern alternatives are recommended.
📖 Summary
np.sort: returns a sorted copy;a.sort()sorts in-placenp.argsort: returns indices for sorting; useful for sorting multiple arrays by the same ordernp.searchsorted: finds insertion positions in sorted arrays (binary search, O(log n))np.unique: finds unique elements with optional counts, indices, and inversenp.partition: partial sort — faster than full sort for finding top-k elements
📝 Exercises
-
Beginner (Difficulty ⭐): Create an array of 20 random integers 0-99. Sort it, find the indices that would sort it, and find the unique values.
-
Intermediate (Difficulty ⭐⭐): Create two arrays — names and scores. Use
np.argsorton scores to sort both arrays so that the highest-scoring name comes first. -
Advanced (Difficulty ⭐⭐⭐): Use
np.searchsortedto merge two sorted arrays into one sorted array without callingnp.sort. Verify the result is correctly sorted.