Price array
- Algorithms course
- Beginner
- Lesson 34/80
- 4 min
Define the price array and print it unsorted.
Add sorting function
Now we add the sort_prices(prices) function. It sorts prices from smallest to largest using selection sort.
Selection sort finds the smallest price at each step and places it correctly. It continues until the whole array is sorted.
Selection sort implementation
Selection sort uses an outer loop for each position and an inner loop to find the minimum. At each step, one price is placed correctly.
Swapping moves the minimum price to its correct position. This arranges the prices in sorted order.
Practice Apply sorting
Write sort_prices(prices). Sort with selection sort and return. Print [12, 23, 45, 67, 99] with print(sort_prices(init_prices())).
Starter code
def init_prices():
# Return price array
return [99, 45, 12, 67, 23]
def sort_prices(prices):
# SortSample solution
def init_prices():
# Return price array
return [99, 45, 12, 67, 23]
def sort_prices(prices):
# Sort
n = len(prices)
for i in range(n - 1):
min_idx = i
for j in range(i + 1, n):
if prices[j] < prices[min_idx]:
min_idx = j
prices[i], prices[min_idx] = prices[min_idx], prices[i]
return prices
print(sort_prices(init_prices()))Expected output
[12, 23, 45, 67, 99]
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which algorithm does sort_prices use?
- Merge sort
- Selection sort Correct answer
- Bubble sort
- Quick sort
Explanation: It uses selection sort.
2 Finding minimum
At each step, the ____ index is found.
At each step, the min_idx index is found.
Explanation: min_idx is right.
3 Price array: match the terms
| Term | Meaning |
|---|---|
sort_prices |
Sort |
prices |
Array |
min_idx |
Minimum |
swap |
Exchange |