NumPy: Sorting and Searching

Last updated: 2026-08-26

1. What You'll Learn



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 only
Original: [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 only
Indices: [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 only
Grades: ['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



📝 Exercises

  1. 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.

  2. Intermediate (Difficulty ⭐⭐): Create two arrays — names and scores. Use np.argsort on scores to sort both arrays so that the highest-scoring name comes first.

  3. Advanced (Difficulty ⭐⭐⭐): Use np.searchsorted to merge two sorted arrays into one sorted array without calling np.sort. Verify the result is correctly sorted.

Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏