Professional Documents
Culture Documents
Ex 10
Ex 10
Ex 10
To sort the chocolates in the supermarket based on its cost and size in ascending order
using merge sort algorithm.
ALGORITHM:
Input: List of chocolates with their cost and size
Output: Sorted list of chocolates in ascending order based on cost
1. Procedure merge_sort_chocolates(chocolates):
a. If the length of chocolates is greater than 1:
i. Find the middle index (mid) of the chocolates list.
ii. Split the chocolates list into left_half (from the beginning to mid) and right_half (from
mid to the end).
iii. Recursively call merge_sort_chocolates on left_half.
iv. Recursively call merge_sort_chocolates on right_half.
v. Call merge to merge the sorted left_half and right_half into the original chocolates list.
3. Example usage:
a. Initialize a list of chocolates with dictionaries containing 'name', 'cost', and 'size'.
b. Print the list before sorting.
c. Call merge_sort_chocolates with the list of chocolates.
d. Print the list after sorting in ascending order based on cost.
PROGRAM:
def merge_sort_chocolates(chocolates):
if len(chocolates) > 1:
mid = len(chocolates) // 2
left_half = chocolates[:mid]
right_half = chocolates[mid:]
merge_sort_chocolates(left_half)
merge_sort_chocolates(right_half)
# Example usage:
if __name__ == "__main__":
chocolates = [
{'name': 'Milk Chocolate', 'cost': 2.50, 'size': 'Small'},
{'name': 'Dark Chocolate', 'cost': 3.00, 'size': 'Medium'},
{'name': 'White Chocolate', 'cost': 2.00, 'size': 'Large'},
{'name': 'Assorted Chocolates', 'cost': 4.50, 'size': 'Small'}
]
print("Before sorting:")
for chocolate in chocolates:
print(chocolate)
merge_sort_chocolates(chocolates)