Sort and Search
Problem Statement
Sort NumPy arrays and find elements.
Background
- np.sort(arr): Returns sorted copy
- np.argsort(arr): Returns indices that would sort the array
- np.where(condition): Find indices where condition is True
- np.argmax(), np.argmin(): Index of max/min element
Your Task
Write a function sort_and_search(arr) that returns a dictionary with:
- "sorted": Sorted array as list
- "argsort": Indices that would sort the array, as a list
- "argmax": Index of maximum value, as a plain integer
- "argmin": Index of minimum value (first occurrence), as a plain integer
Output Format
Return a dictionary with exactly these four keys.
Example
[3, 1, 4, 1, 5, 9, 2, 6]
{'sorted': [1, 1, 2, 3, 4, 5, 6, 9], 'argsort': [1, 3, 6, 0, 2, 4, 7, 5], 'argmax': 5, 'argmin': 1}- Input:
arris a 1D array of 8 values, indexed to : . - Sorted: the same 8 values in ascending order,
[1, 1, 2, 3, 4, 5, 6, 9]. Both 1s stay. - Argsort: instead of values, list the positions they came from, in sorted order. The smallest value 1 sits at positions 1 and 3, then 2 is at 6, 3 at 0, 4 at 2, 5 at 4, 6 at 7 and 9 at 5, giving
[1, 3, 6, 0, 2, 4, 7, 5]. Reading at those positions gives the sorted list. - Argmax / argmin: the largest value, 9, is at position 5, and the smallest, 1, first appears at position 1, so
argmaxis 5 andargminis 1. - Notice that with ties, position 1 beats position 3 for the minimum: it is the first occurrence that counts. Here the maximum 9 is unique, so the last entry of
argsortis theargmaxposition 5, and in this sample its first entry, 1, is also theargminposition.
Constraints
- Use np.sort(), np.argsort(), np.argmax(), np.argmin()
- Array will have at least 1 element