CodeBlanks Logo Icon CodeBlanks

Apply sorting

Sort prices with bubble sort.

Print the result

Now we add print_sorted(prices). It prints each sorted price on its own line.

This function calls sort_prices and prints the result with a for loop. This visualizes the sorting result.

Printing with a for loop

A for loop is used to print the sorted array. Each element is passed to the print function in order.

This approach makes each sorted price appear on its own line. The output is clean and readable.

Practice Print result

Write print_sorted(prices). Sort and print each price on its own line. Call print_sorted(init_prices()) to print 12, 23, 45, 67, 99.

Starter code

solution.py
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
def print_sorted(prices):
    # Sort and print

Sample solution

solution.py
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
def print_sorted(prices):
    # Sort and print
    sorted_prices = sort_prices(prices)
    for p in sorted_prices:
        print(p)
print_sorted(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 Sort call

Question
sorted_prices = ____(prices)
Answer
sorted_prices = sort_prices(prices)

Explanation: sort_prices is right.

2 Apply sorting: match the terms

Term Meaning
print_sorted Print
sort_prices Sort
for p in Loop
print(p) Output

3 What does print_sorted do?

  • Sorts and prints Correct answer
  • Only sorts
  • Only prints
  • Averages

Explanation: It sorts and prints.

All lessons in Beginner