Advertisements
Advertisements
Question
A list contains Item_code, Item_name and price. Sort the list :
- In ascending order of price using Bubble sort.
- In descending order of qty using Insertion sort.
Code Writing
Advertisements
Solution
For part (b), the record must also contain qty. Therefore, each item is assumed to be stored as [item_code, item_name, price, qty].
def bubble_sort_price(items):
"""Sort items in ascending order of price."""
for i in range(len(items) - 1):
swapped = False
for j in range(len(items) - 1 - i):
if items[j][2] > items[j + 1][2]:
items[j], items[j + 1] = items[j + 1], items[j]
swapped = True
if not swapped:
break
return items
def insertion_sort_quantity(items):
"""Sort items in descending order of quantity."""
for i in range(1, len(items)):
current_item = items[i]
j = i - 1
# Shift smaller quantities rightward
while j >= 0 and items[j][3] < current_item[3]:
items[j + 1] = items[j]
j -= 1
items[j + 1] = current_item
return items
items = [
[101, "Pen", 20, 50],
[102, "Book", 75, 20],
[103, "Pencil", 10, 100]
]
print("Price ascending:", bubble_sort_price(items.copy()))
print("Quantity descending:", insertion_sort_quantity(items.copy()))
Price ascending: [[103, 'Pencil', 10, 100], [101, 'Pen', 20, 50], [102, 'Book', 75, 20]]
Quantity descending: [[103, 'Pencil', 10, 100], [101, 'Pen', 20, 50], [102, 'Book', 75, 20]]shaalaa.com
Is there an error in this question or solution?
