You are on page 1of 3

Ex 8: Insertion Sort – Contacts

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

while j >= 0 and current_contact['first_name'] < contacts[j]['first_name']:


contacts[j + 1] = contacts[j]
j -= 1
contacts[j + 1] = current_contact
# Example usage:
if __name__ == "__main__":
contacts = [
{'first_name': 'John', 'last_name': 'Doe'},
{'first_name': 'Alice', 'last_name': 'Smith'},
{'first_name': 'Bob', 'last_name': 'Johnson'},
{'first_name': 'Eve', 'last_name': 'Williams'}
]

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'}

You might also like