np.argsort() for sort indices in NumPy - Time & Space Complexity
Start learning this pattern below
Jump into concepts and practice - no test required
We want to understand how the time needed to find sorted indices changes as the input array grows.
Specifically, how does np.argsort() behave when sorting larger arrays?
Analyze the time complexity of the following code snippet.
import numpy as np
arr = np.random.rand(1000)
sorted_indices = np.argsort(arr)
This code creates an array of 1000 random numbers and finds the indices that would sort the array.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The sorting algorithm compares and rearranges elements to find the order.
- How many times: The sorting process involves multiple comparisons and swaps, repeating many times depending on array size.
As the array size grows, the number of operations grows faster than just a simple increase.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 30 to 40 operations |
| 100 | About 600 to 700 operations |
| 1000 | About 10,000 to 12,000 operations |
Pattern observation: The operations grow faster than the input size itself, roughly multiplying by a bit more than n each time.
Time Complexity: O(n log n)
This means the time needed grows a bit faster than the size of the array, but not as fast as checking every pair individually.
[X] Wrong: "Sorting indices with np.argsort() takes time proportional to the array size only (O(n))."
[OK] Correct: Sorting requires comparing elements multiple times, so it takes more time than just looking at each element once.
Knowing how sorting scales helps you explain performance when working with data. It shows you understand how algorithms behave with bigger inputs.
"What if we used np.argpartition() instead of np.argsort()? How would the time complexity change?"
Practice
np.argsort() function return when applied to a numpy array?Solution
Step 1: Understand the purpose of
This function does not sort the array directly but returns the indices that would sort the array.np.argsort()Step 2: Differentiate from sorting functions
Unlikenp.sort()which returns the sorted array,np.argsort()returns the order of indices to achieve that sorting.Final Answer:
An array of indices that would sort the original array -> Option DQuick Check:
np.argsort()= indices order [OK]
- Confusing argsort with sort and expecting sorted values
- Thinking argsort returns the maximum or minimum value
- Assuming argsort returns a scalar instead of an array
arr using a NumPy function?Solution
Step 1: Identify the numpy function for argsort
The functionnp.argsort()is called with the array as argument:np.argsort(arr).Step 2: Differentiate from other methods
arr.argsort()is an array method (not the NumPy function), whilenp.sort(arr)returns sorted values, andarr.sort()sorts in place.Final Answer:
np.argsort(arr) -> Option BQuick Check:
Correct function call = np.argsort(arr) [OK]
- Using arr.argsort() (array method instead of NumPy function)
- Confusing np.sort() with np.argsort()
- Using arr.sort() which sorts in place and returns None
import numpy as np arr = np.array([40, 10, 30, 20]) indices = np.argsort(arr) print(indices)
What will be the output?
Solution
Step 1: Understand the array and sorting order
The array is [40, 10, 30, 20]. Sorting it ascending gives [10, 20, 30, 40].Step 2: Find indices that sort the array
10 is at index 1, 20 at index 3, 30 at index 2, and 40 at index 0. So, indices are [1, 3, 2, 0].Final Answer:
[1 3 2 0] -> Option AQuick Check:
Sorted indices = [1 3 2 0] [OK]
- Confusing sorted values with indices
- Reversing the order of indices
- Using sorted array instead of indices
import numpy as np arr = np.array([3, 1, 2]) indices = arr.argsort() print(indices)
Solution
Step 1: Check if
In numpy, arrays do have anargsort()is a valid numpy array methodargsort()method, soarr.argsort()is valid.Step 2: Verify code correctness
The code will run and print the indices that sort the array, which are [1, 2, 0].Final Answer:
The code will run correctly and print the sorted indices -> Option AQuick Check:
arr.argsort() is valid and works [OK]
- Assuming argsort() is only in np module, not array method
- Thinking array must be sorted before argsort()
- Confusing Python 2 print syntax with Python 3
names = np.array(['apple', 'banana', 'cherry', 'date']) prices = np.array([3.5, 2.0, 4.0, 1.5])
You want to list the fruit names sorted by their prices in ascending order. Which code snippet correctly achieves this?
Solution
Step 1: Use
This returns indices that sort prices ascending.np.argsort(prices)to get indices that sort pricesStep 2: Use these indices to reorder
Indexingnamesnameswith these indices sorts names by price.Final Answer:
sorted_names = names[np.argsort(prices)] -> Option CQuick Check:
Index names by argsort(prices) to sort by price [OK]
- Trying to sort names directly without using indices
- Using np.sort(names) which sorts names alphabetically
- Indexing with sorted prices instead of indices
