Sort Array and Argsort Practice Problem
This data science coding problem helps you practice Array Manipulation, sort array and argsort, and implementation skills. Read the problem statement, write your solution, and strengthen your understanding of Array Manipulation.
- Problem ID: 60
- Problem key: 60-sort-array-and-argsort
- URL: https://datacrack.app/solve/60-sort-array-and-argsort
- Difficulty: easy
- Topic: Array Manipulation
- Module: NumPy Foundations
Problem Statement
# 🧩 Sort Array and Argsort
---
### 🎯 Goal
`np.argsort()` is one of the most useful NumPy functions in practice — it returns the **indices** that would sort an array.
This lets you sort one array and apply the same ordering to another related array, like sorting scores while keeping the matching labels/names in the correct order.
It powers top-K retrieval, ranking, and index-based reordering.
---
### 🔍 The Difference: `sort` vs `argsort`
```python
arr = np.array([3, 1, 4, 1, 5])
np.sort(arr) # → [1, 1, 3, 4, 5] — sorted values
np.argsort(arr) # → [1, 3, 0, 2, 4] — indices that sort arr
arr[np.argsort(arr)] # → [1, 1, 3, 4, 5] — same as np.sort
```
---
### 💻 Task
Implement `sort_and_argsort(data)`.
---
### 📥 Input
- `data`: list of numbers
### 📤 Output
- dict with:
- `"sorted_asc"`: values sorted ascending
- `"sorted_desc"`: values sorted descending
- `"argsort_asc"`: indices that sort ascending
---
### 🧩 Starter Code
```python
import numpy as np
def sort_and_argsort(data):
"""
Sort an array and return sorted values and sorting indices.
Args:
data (list): Input numbers
Returns:
dict: {"sorted_asc", "sorted_desc", "argsort_asc"}
"""
arr = np.array(data)
# 🧠 TODO
pass
```
---
### 🔑 Key Concepts
- `np.sort(arr)` — returns a sorted copy (does not modify in place)
- `arr.sort()` — sorts in place (modifies arr)
- `np.argsort(arr)` — returns indices; use `arr[np.argsort(arr)]` to reconstruct sorted arrayStarter Code
import numpy as np
def sort_and_argsort(data):
"""
Sort an array and return sorted values and sorting indices.
Args:
data (list): Input numbers
Returns:
dict: {"sorted_asc", "sorted_desc", "argsort_asc"}
"""
arr = np.array(data)
# 🧠 TODO
pass