Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python3
- # -*- coding: utf-8 -*-
- # Filename: bubble_sort_demo.py
- # Version: 1.0.0
- # Author: Jeoi Reqi
- """
- Description:
- This script demonstrates the bubble sort algorithm by sorting an array of integers.
- Requirements:
- - Python 3.x
- Functions:
- - bubble_sort(arr):
- Perform bubble sort on the given list `arr`.
- Usage:
- - Run the script to see the bubble sort algorithm in action.
- Additional Notes:
- - Bubble sort is not efficient for large datasets compared to more advanced sorting algorithms.
- """
- def bubble_sort(arr):
- """
- Perform bubble sort on the given list `arr` in place.
- Args:
- arr (list): List of integers to be sorted in place.
- Returns:
- None. The list `arr` is sorted in place.
- Example Output:
- :: BUBBLE SORTING DEMO ::
- Original array: [69, 42, 25, 12, 22, 17, 79, 90, 7, 99]
- Sorted array: [ 7, 12, 17, 22, 25, 42, 69, 79, 90, 99]
- Bubble Sorting Complete!
- Exiting Program... GoodBye!
- """
- n = len(arr)
- for i in range(n):
- for j in range(0, n-i-1):
- if arr[j] > arr[j+1]:
- arr[j], arr[j+1] = arr[j+1], arr[j]
- def main():
- """
- Main function to demonstrate bubble sort.
- It initializes an example array, sorts it using bubble_sort function,
- and prints the original and sorted arrays.
- """
- print("\n\t\t:: BUBBLE SORTING DEMO ::\n")
- # Example array to sort
- arr = [69, 42, 25, 12, 22, 17, 79, 90, 7, 99]
- # Print the original array
- original_arr_str = "["
- for index, num in enumerate(arr):
- if index == 0:
- original_arr_str += f"{num:2}" # Add a leading space for single-digit numbers
- else:
- original_arr_str += f", {num:2}" # Add a leading space for single-digit numbers
- original_arr_str += "]"
- print("Original array:", original_arr_str)
- # Sort the array using bubble sort
- bubble_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 a leading space for single-digit numbers
- else:
- sorted_arr_str += f", {num:2}" # Add a leading space for single-digit numbers
- sorted_arr_str += "]"
- print("Sorted array: ", sorted_arr_str)
- # Print completion message
- print("\nBubble Sorting Complete!\n\n\tExiting Program... GoodBye!")
- if __name__ == "__main__":
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement