Sorting and Unique
Sort Array
Order a 6-element list ascending by repeatedly picking the smallest remaining
value. Each iteration takes min(remaining), appends it to result, and
removes it from remaining. The trace shows remaining shrinking and
result growing one element at a time.
By hand
Initialize remaining as a copy of values. Repeat len(values) times:
find min(remaining), append it to result, remove it from remaining.
naive.py
values = [3, 1, 4, 1, 5, 9]
remaining = list(values)
result = []
for _ in range(len(values)):
m = min(remaining)
result.append(m)
remaining.remove(m)
print('RESULT:', result)
With NumPy
np.sort(a) returns a new sorted array. The original a is unchanged.
library.py
import numpy as np
values = [3, 1, 4, 1, 5, 9]
a = np.array(values)
result = np.sort(a)
print('a: shape:', a.shape, 'dtype:', a.dtype, 'values:', a.tolist())
print('result: shape:', result.shape, 'dtype:', result.dtype, 'values:', result.tolist())
print('RESULT:', result.tolist())
a: shape: (6,) dtype: int64 values: [3, 1, 4, 1, 5, 9]
result: shape: (6,) dtype: int64 values: [1, 1, 3, 4, 5, 9]
RESULT: [1, 1, 3, 4, 5, 9]
Implementation notes
np.sort(a)returns a copy —ais unmodified. To sort in place usea.sort()(a method on the array), which modifiesaand returnsNone.- Default sort order is ascending. For descending order use
np.sort(a)[::-1](sort first, then reverse the result). - This lesson teaches sort usage. The underlying algorithms (quicksort, mergesort, heapsort, timsort) are covered in the DSA track.
- Shape, dtype, and values are shown explicitly here because
ndarray.__repr__output varies with NumPy version and print options.