Concept Flow - np.sort() for sorting arrays
Input Array
Call np.sort()
Compare elements
Rearrange elements in order
Return sorted array
np.sort() takes an array, compares elements, rearranges them in ascending order, and returns the sorted array.
Jump into concepts and practice - no test required
import numpy as np arr = np.array([3, 1, 4, 1, 5]) sorted_arr = np.sort(arr) print(sorted_arr)
| Step | Array State | Action | Result |
|---|---|---|---|
| 1 | [3, 1, 4, 1, 5] | Start sorting | [3, 1, 4, 1, 5] |
| 2 | [3, 1, 4, 1, 5] | Compare 3 and 1, swap | [1, 3, 4, 1, 5] |
| 3 | [1, 3, 4, 1, 5] | Compare 3 and 4, no swap | [1, 3, 4, 1, 5] |
| 4 | [1, 3, 4, 1, 5] | Compare 4 and 1, swap | [1, 3, 1, 4, 5] |
| 5 | [1, 3, 1, 4, 5] | Compare 4 and 5, no swap | [1, 3, 1, 4, 5] |
| 6 | [1, 3, 1, 4, 5] | Compare 3 and 1, swap | [1, 1, 3, 4, 5] |
| 7 | [1, 1, 3, 4, 5] | No more swaps needed | [1, 1, 3, 4, 5] |
| 8 | [1, 1, 3, 4, 5] | Return sorted array | [1, 1, 3, 4, 5] |
| Variable | Start | After Step 2 | After Step 4 | After Step 6 | Final |
|---|---|---|---|---|---|
| arr | [3, 1, 4, 1, 5] | [3, 1, 4, 1, 5] | [3, 1, 4, 1, 5] | [3, 1, 4, 1, 5] | [3, 1, 4, 1, 5] |
| sorted_arr | N/A | N/A | N/A | N/A | [1, 1, 3, 4, 5] |
np.sort(array) → returns a sorted copy of the array in ascending order. Original array stays unchanged. Works on 1D and multi-dimensional arrays. Default sorting is ascending. Use sorted_arr = np.sort(arr) to keep sorted result.
np.sort() function do when applied to a NumPy array?np.sort() function returns a new sorted array and does not modify the original array.np.sort() sorts elements in ascending order.arr using np.sort()?np.sort(arr).arr.sort() sorts in place but is a method, not np.sort(). np.sort(arr, axis=1) is invalid for 1D arrays. arr.sorted() is not a valid method.import numpy as np arr = np.array([[3, 1, 2], [6, 4, 5]]) sorted_arr = np.sort(arr, axis=1) print(sorted_arr)
axis=1 sorts each row independently in ascending order.import numpy as np arr = np.array([3, 1, 2]) sorted_arr = np.sort(arr, axis=1) print(sorted_arr)
arr is 1D, so it only has axis 0.axis=1 on a 1D array causes an error because axis 1 does not exist.data = np.array([[7, 2, 9], [4, 5, 1], [8, 3, 6]]), how can you sort the entire array as if it were a flat list, then reshape it back to the original shape?axis=None in np.sort() sorts the array as a flat 1D array..reshape(data.shape) to restore the 2D shape after sorting.