/Curriculum/IntermediateSearching & Sorting

24. NumPy SortingIntermediate

Sort 1D and 2D arrays with np.sort() and retrieve sorted index order with np.argsort().

12 mins

Concept Overview

`np.sort()` returns a sorted copy of an array using optimized C-level quicksort. `np.argsort()` returns the index order that sorts the array.

Hardware Mental Model

`np.sort` organizes runners by their finishing times. `np.argsort` lists the jersey numbers of runners in order of who crossed the finish line first.

Key Concepts (1)Click snippet to load in editor

`np.sort(arr)` returns sorted values. `np.argsort(arr)` returns an index permutation array, which is essential for sorting parallel columns in datasets.

s = np.sort(arr); idx = np.argsort(arr)

⚠ Common Mistakes & Pitfalls

Avoid these frequent beginner syntax and logic traps
❌ Incorrect:arr.sort() # Mutates original array in place without returning it
✓ Correct:sorted_arr = np.sort(arr) # Returns sorted copy safely

`np.sort(arr)` returns a new array; `arr.sort()` mutates in-place and returns None.

Pro Tip: Use `np.sort(arr)` when you wish to preserve the original array.

📌 Quick Revision

Core takeaway points from this topic
`np.sort(arr)`: Returns a sorted copy.
`np.argsort(arr)`: Returns indices that would sort the array.
`np.sort(arr)[::-1]`: Sorts in descending order.
`axis=0` / `axis=1`: Sorts along specified matrix dimension.
Editor: 24. NumPy Sorting
Python ● Ready
Initializing Python IDE...
Ctrl+Enter
Execution Result
Click "RUN CODE" to execute and inspect array state

🎯 Try It Yourself: Practice Challenge

Hands-on Mode

Solve the objective below using NumPy vectorized syntax

Objective:Sort an Array

Create `arr = np.array([30, 10, 50, 20])`, sort it using `np.sort(arr)`, and print.

Expected Output Target:[10 20 30 50]
Practice Workspace
Python ● Ready
Initializing Python IDE...
Ctrl+Enter
Execution Result
Click "RUN CODE" to execute and inspect array state