Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python3
- # -*- coding: utf-8 -*-
- # Filename: merge_sort_demo.py
- # Version: 1.0.0
- # Author: Jeoi Reqi
- """
- Description:
- This script demonstrates the Merge Sort algorithm by sorting an array of integers.
- Requirements:
- - Python 3.x
- Functions:
- - merge_sort(arr):
- Perform merge sort on the given list `arr`.
- Usage:
- - Run the script to see the Merge Sort algorithm in action.
- Example:
- :: MERGE SORTING DEMO ::
- Original array: [12, 11, 13, 5, 6, 7]
- Sorted array: [ 5, 6, 7, 11, 12, 13]
- Merge Sorting Complete!
- Exiting Program... GoodBye!
- Additional Notes:
- - Merge Sort is an efficient sorting algorithm with a time complexity of O(n log n).
- """
- def merge_sort(arr):
- """
- Perform merge 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.
- """
- if len(arr) > 1:
- mid = len(arr) // 2
- L = arr[:mid]
- R = arr[mid:]
- merge_sort(L)
- merge_sort(R)
- i = j = k = 0
- while i < len(L) and j < len(R):
- if L[i] < R[j]:
- arr[k] = L[i]
- i += 1
- else:
- arr[k] = R[j]
- j += 1
- k += 1
- while i < len(L):
- arr[k] = L[i]
- i += 1
- k += 1
- while j < len(R):
- arr[k] = R[j]
- j += 1
- k += 1
- def main():
- """
- Main function to demonstrate merge sort.
- It initializes an example array, sorts it using merge_sort function,
- and prints the original and sorted arrays.
- """
- print("\n\t\t:: MERGE SORTING DEMO ::\n")
- # Example array to sort
- arr = [12, 11, 13, 5, 6, 7]
- # 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 merge sort
- merge_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("\nMerge Sorting Complete!\n\n\tExiting Program... GoodBye!")
- if __name__ == "__main__":
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement