NumPy Sorting and Searching Arrays
NumPy provides efficient functions for sorting array elements and searching for specific values or positions. Sorting helps organize numerical data, while searching helps locate matching elements, insertion positions, and extreme values. In this lesson, you will learn ascending and descending sorting, multidimensional sorting, index-based sorting, binary search, and practical searching techniques.
1. Introduction to Sorting Arrays
Sorting arranges array elements in a specific order. Numerical arrays are commonly sorted in ascending order, from smallest to largest. Sorting can make data easier to inspect, compare, and analyze.
Output:
The np.sort() function returns a sorted copy of the
array. The original array remains unchanged.
Benefits of Sorting
- Organizes numerical values in ascending or descending order.
- Makes minimum and maximum values easier to inspect.
- Helps prepare data for binary search.
- Supports ranking and data analysis tasks.
2. Sorting in Ascending and Descending Order
By default, np.sort() sorts numerical values in ascending
order. To obtain descending order, reverse the sorted result using
slicing.
Output:
[::-1] reverses the
order of elements. Sorting first and then reversing is a simple way
to create descending numerical order.
3. Understanding np.sort() and the axis Parameter
For a multidimensional array, the axis parameter controls
the direction of sorting. By default, NumPy sorts along the last axis.
Output:
| Expression | Behavior |
|---|---|
np.sort(data) |
Sorts along the last axis by default. |
np.sort(data, axis=0) |
Sorts each column independently. |
np.sort(data, axis=1) |
Sorts each row independently. |
np.sort(data, axis=None) |
Sorts all elements and returns a flattened one-dimensional array. |
4. Sorting Without Losing the Original Data
The np.sort() function returns a sorted copy. If you use
the array method sort(), the existing array is sorted
in place.
Output:
np.sort(values) when
you need to preserve the original ordering. Use values.sort()
when modifying the original array is intended.
5. Sorting with Different Algorithms
NumPy supports different sorting algorithms. The
kind parameter lets you select an algorithm when
needed.
| Algorithm | General Description |
|---|---|
quicksort |
A quick comparison-based sorting algorithm. |
heapsort |
A comparison-based algorithm using a heap structure. |
mergesort |
A stable sorting option supported by NumPy. |
stable |
Requests a stable sort that preserves the relative order of equal keys. |
Output:
All three examples produce the same numerical order. The algorithm choice affects implementation behavior and can matter for performance or stability requirements.
6. Sorting Indices with np.argsort()
Sometimes you need the positions that would sort an array rather than
the sorted values themselves. The np.argsort() function
returns these indices.
Output:
The first sorted value, 65, originally appeared at index 2. The next value, 74, originally appeared at index 4. These positions are represented by the returned index array.
When Is argsort() Useful?
- Ranking students by marks.
- Ordering records according to a numerical score.
- Reordering one array based on another array's values.
- Finding the indices of the lowest or highest values.
7. Searching for Values with np.where()
The np.where() function can locate positions where a
condition is true. It is useful for finding exact matches or
identifying values that meet a threshold.
Output:
Find Values Above a Threshold
Output:
8. Searching in Sorted Arrays with np.searchsorted()
The np.searchsorted() function finds an insertion position
that keeps a sorted array in order. It uses binary-search logic and
assumes the input array is sorted.
Output:
Left and Right Insertion Positions
Output:
The left position is before the existing values equal to 20. The right position is after all of them.
np.searchsorted()
on an unsorted array unless you explicitly provide valid sorting-order
information. Otherwise, the insertion position may not be meaningful.
9. Finding the Smallest and Largest Values
NumPy offers several ways to identify extreme values. The functions
np.argmin() and np.argmax() return the
positions of the minimum and maximum values.
Output:
Find the Three Largest Values
The np.partition() function can place the smallest or
largest values into their correct partition positions without fully
sorting every element.
Output:
Partitioning does not sort every element. Sorting the selected three values afterward displays them in descending order.
10. Practical Project: Ranking Student Marks
In this project, we will sort student marks, find their ranking order, and identify the highest and lowest scores.
Output:
Project Learning Outcomes
- Sort student marks in ascending order.
- Use
np.argsort()to get ranking indices. - Keep student names aligned with their corresponding marks.
- Use
np.max()andnp.min()to identify extreme scores.
11. Common Mistakes and Best Practices
Confusing sort() and argsort()
np.sort() returns sorted values, whereas
np.argsort() returns the indices that describe the
sorted order.
Searching an Unsorted Array with searchsorted()
Ensure the input is sorted before using np.searchsorted(),
or provide the appropriate sorter argument when working with an
indirect ordering.
Overwriting the Original Array
np.sort() returns a sorted copy. The array method
array.sort() modifies the original array in place.
Sorting the Wrong Axis
For multidimensional arrays, choose the axis according to whether you need to sort each row, each column, or the complete array.
Assuming Duplicate Values Have a Unique Position
A value may appear more than once. Use np.where()
when you need every index satisfying a condition.
12. Practice Exercises
Exercise 1: Basic Sorting
Create an array containing [45, 12, 89, 23, 67, 34].
Sort it in ascending and descending order.
Exercise 2: Matrix Sorting
Create a 3 by 3 matrix and sort its rows using
axis=1. Then sort its columns using axis=0.
Exercise 3: Sorting Indices
Use np.argsort() to find the indices that would sort
a marks array. Use those indices to arrange student names by marks.
Exercise 4: Search for Values
Use np.where() to find every occurrence of a target
value in an array.
Exercise 5: Insertion Position
Use np.searchsorted() to find the insertion position
of 35 in a sorted array containing [10, 20, 30, 40, 50].
Exercise 6: Student Ranking
Create marks for Samadhan, Pradnya, and Samiksha. Print their
ranking from highest to lowest using np.argsort().
Summary
In this lesson, you learned to sort NumPy arrays using
np.sort(), control sorting direction with slicing,
and sort multidimensional arrays along a selected axis. You also
explored in-place sorting and index-based sorting with
np.argsort().
You practiced locating values with np.where(),
finding insertion positions with np.searchsorted(),
and identifying extreme values with np.argmin() and
np.argmax(). These techniques are useful for ranking,
searching, and organizing numerical datasets.