Skip to content

Commit 736935a

Browse files
authored
[Term Entry] NumPy ndarray: .searchsorted()
* Create new searchsorted() term entry under ndarray in Numpy docs * content fix, added codebyte * Update searchsorted.md * Update searchsorted.md ---------
1 parent c5079fa commit 736935a

File tree

1 file changed

+64
-0
lines changed

1 file changed

+64
-0
lines changed
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
---
2+
Title: '.searchsorted()'
3+
Description: 'Returns the index where a value should be inserted to maintain order.'
4+
Subjects:
5+
- 'Computer Science'
6+
- 'Data Science'
7+
Tags:
8+
- 'Arrays'
9+
- 'Binary Search'
10+
- 'NumPy'
11+
- 'Search'
12+
CatalogContent:
13+
- 'learn-python-3'
14+
- 'paths/computer-science'
15+
---
16+
17+
In NumPy, the **`.searchsorted()`** function returns the index where a value should be inserted to maintain order.
18+
19+
## Syntax
20+
21+
```pseudo
22+
ndarray.searchsorted(value, side='left', sorter=None)
23+
```
24+
25+
**Parameters:**
26+
27+
- `value` (array_like): Values to insert into the array.
28+
- `side` (default=`'left'`, optional): Determines whether to return the first suitable location (`'left'`) or last (`'right'`).
29+
- `sorter` (1-D array_like, optional): Specifies a pre-sorted index array for the search (used if the array isn’t sorted).
30+
31+
**Return value:**
32+
33+
The index (or indices) where `values` should be inserted to maintain order.
34+
35+
## Example
36+
37+
In this example, `.searchsorted()` finds the index where the value `3` should be inserted to keep the array sorted:
38+
39+
```py
40+
import numpy as np
41+
42+
arr = np.array([11, 22, 33, 44, 55])
43+
index = arr.searchsorted(33)
44+
print(index)
45+
```
46+
47+
The result is `2`, which is the position of the first `33` in the sorted array:
48+
49+
```shell
50+
2
51+
```
52+
53+
## Codebyte Example
54+
55+
In this codebyte example, `.searchsorted()` finds where a new test score should be inserted in a sorted list of scores:
56+
57+
```codebyte/python
58+
import numpy as np
59+
60+
scores = np.array([55, 60, 65, 70, 75])
61+
new_score = 68
62+
position = scores.searchsorted(new_score)
63+
print(position)
64+
```

0 commit comments

Comments
 (0)