Professional Documents
Culture Documents
Ex 8
Ex 8
To sort the contact names in your phone in ascending order based on the first name
using insertion sort algorithm
ALGORITHM:
Input: List of contacts
Output: Sorted list of contacts based on first name
1. Procedure insertion_sort_contacts(contacts):
a. For i from 1 to length of contacts - 1:
i. Set current_contact as contacts[i].
ii. Set j as i - 1.
iii. While j is greater than or equal to 0 and current_contact['first_name'] <
contacts[j]['first_name']:
- Move contacts[j] to contacts[j + 1].
- Decrement j by 1.
iv. Set contacts[j + 1] as current_contact.
2. Example usage:
a. Initialize a list of contacts with dictionaries containing 'first_name' and 'last_name'.
b. Print the list before sorting.
c. Call insertion_sort_contacts with the list of contacts.
d. Print the list after sorting.
PROGRAM:
def insertion_sort_contacts(contacts):
for i in range(1, len(contacts)):
current_contact = contacts[i]
j=i-1
print("Before sorting:")
for contact in contacts:
print(contact)
insertion_sort_contacts(contacts)
print("\nAfter sorting:")
for contact in contacts:
print(contact)
OUTPUT:
Before sorting:
{'first_name': 'John', 'last_name': 'Doe'}
{'first_name': 'Alice', 'last_name': 'Smith'}
{'first_name': 'Bob', 'last_name': 'Johnson'}
{'first_name': 'Eve', 'last_name': 'Williams'}
After sorting:
{'first_name': 'Alice', 'last_name': 'Smith'}
{'first_name': 'Bob', 'last_name': 'Johnson'}
{'first_name': 'Eve', 'last_name': 'Williams'}
{'first_name': 'John', 'last_name': 'Doe'}