Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python3
- # -*- coding: utf-8 -*-
- # Filename: insertion_sort_demo.py
- # Version: 1.0.0
- # Author: Jeoi Reqi
- """
- Description:
- This script demonstrates the Insertion Sort algorithm by sorting an array of integers.
- Requirements:
- - Python 3.x
- Functions:
- - insertion_sort(arr):
- Perform insertion sort on the given list `arr`.
- Usage:
- - Run the script to see the Insertion Sort algorithm in action.
- Example:
- :: INSERTION SORTING DEMO ::
- Original array: [12, 11, 13, 5, 6]
- Sorted array: [ 5, 6, 11, 12, 13]
- Insertion Sorting Complete!
- Exiting Program... GoodBye!
- Additional Notes:
- - Insertion Sort is an efficient sorting algorithm for small datasets with a time complexity of O(n^2).
- """
- def insertion_sort(arr):
- """
- Perform insertion sort on the given list `arr` in place.
- Args:
- arr (list): List of integers to be sorted.
- Returns:
- None. The list `arr` is sorted in place.
- """
- for i in range(1, len(arr)):
- key = arr[i]
- j = i - 1
- while j >= 0 and key < arr[j]:
- arr[j + 1] = arr[j]
- j -= 1
- arr[j + 1] = key
- def main():
- """
- Main function to demonstrate insertion sort.
- It initializes an example array, sorts it using insertion_sort function,
- and prints the original and sorted arrays.
- """
- print("\n\t\t:: INSERTION SORTING DEMO ::\n")
- # Example array to sort
- arr = [12, 11, 13, 5, 6]
- # Print the original array
- original_arr_str = "["
- for index, num in enumerate(arr):
- if index == 0:
- original_arr_str += f"{num:2}" # Add one space for single-digit numbers
- else:
- original_arr_str += f", {num:2}" # Add one space for single-digit numbers
- original_arr_str += "]"
- print("Original array:", original_arr_str)
- # Sort the array using insertion sort
- insertion_sort(arr)
- # Print the sorted array
- sorted_arr_str = "["
- for index, num in enumerate(arr):
- if index == 0:
- sorted_arr_str += f"{num:2}" # Add one space for single-digit numbers
- else:
- sorted_arr_str += f", {num:2}" # Add one space for single-digit numbers
- sorted_arr_str += "]"
- print("Sorted array: ", sorted_arr_str)
- # Print completion message
- print("\nInsertion Sorting Complete!\n\n\tExiting Program... GoodBye!")
- if __name__ == "__main__":
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement