Advertisement
Python253

radix_sort_demo

Jun 24th, 2024
421
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.46 KB | None | 0 0
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. # Filename: radix_sort_demo.py
  4. # Version: 1.0.0
  5. # Author: Jeoi Reqi
  6.  
  7. """
  8. Description:
  9.    This script demonstrates the Radix Sort algorithm by sorting an array of integers.
  10.  
  11. Requirements:
  12.    - Python 3.x
  13.  
  14. Functions:
  15.    - counting_sort(arr, exp):
  16.        Perform counting sort on the array `arr` based on the exponent `exp`.
  17.  
  18.    - radix_sort(arr):
  19.        Perform radix sort on the given list `arr` using counting_sort as a subroutine.
  20.  
  21. Usage:
  22.    - Run the script to see the Radix Sort algorithm in action.
  23.  
  24. Example Output:
  25.  
  26.                :: RADIX SORTING DEMO ::
  27.  
  28.        Original array: [170,  45,  75,  90, 802,  24,   2,  66]
  29.        Sorted array:   [  2,  24,  45,  66,  75,  90, 170, 802]
  30.  
  31.        Radix Sorting Complete!
  32.  
  33.            Exiting Program...   GoodBye!
  34.  
  35. Additional Notes:
  36.    - Radix Sort is efficient for sorting integers, especially when the range of numbers is known and limited.
  37. """
  38.  
  39. def counting_sort(arr, exp):
  40.     """
  41.    Perform counting sort on the array `arr` based on the exponent `exp`.
  42.  
  43.    Args:
  44.        arr (list): List of integers to be sorted.
  45.        exp (int): Exponent used to sort elements.
  46.  
  47.    Returns:
  48.        None. The list `arr` is sorted in place based on the exponent `exp`.
  49.    """
  50.     n = len(arr)
  51.     output = [0] * n
  52.     count = [0] * 10
  53.  
  54.     for i in range(n):
  55.         index = arr[i] // exp
  56.         count[index % 10] += 1
  57.  
  58.     for i in range(1, 10):
  59.         count[i] += count[i - 1]
  60.  
  61.     i = n - 1
  62.     while i >= 0:
  63.         index = arr[i] // exp
  64.         output[count[index % 10] - 1] = arr[i]
  65.         count[index % 10] -= 1
  66.         i -= 1
  67.  
  68.     for i in range(n):
  69.         arr[i] = output[i]
  70.  
  71. def radix_sort(arr):
  72.     """
  73.    Perform radix sort on the given list `arr` using counting_sort as a subroutine.
  74.  
  75.    Args:
  76.        arr (list): List of integers to be sorted in place.
  77.  
  78.    Returns:
  79.        None. The list `arr` is sorted in place using radix sort.
  80.    """
  81.     max1 = max(arr)
  82.     exp = 1
  83.     while max1 // exp > 0:
  84.         counting_sort(arr, exp)
  85.         exp *= 10
  86.  
  87. def main():
  88.     """
  89.    Main function to demonstrate radix sort.
  90.  
  91.    It initializes an example array, sorts it using radix_sort function,
  92.    and prints the original and sorted arrays.
  93.    """
  94.     print("\n\t\t:: RADIX SORTING DEMO ::\n")
  95.    
  96.     # Example array to sort
  97.     arr = [170, 45, 75, 90, 802, 24, 2, 66]
  98.  
  99.     # Print the original array
  100.     original_arr_str = "["
  101.     for index, num in enumerate(arr):
  102.         if index == 0:
  103.             original_arr_str += f"{num:3}"  # Add two spaces for single-digit numbers
  104.         else:
  105.             original_arr_str += f", {num:3}" if num >= 10 else f",  {num:2}"  # Add one space for two-digit numbers
  106.     original_arr_str += "]"
  107.     print("Original array:", original_arr_str)
  108.  
  109.     # Sort the array using radix sort
  110.     radix_sort(arr)
  111.  
  112.     # Print the sorted array
  113.     sorted_arr_str = "["
  114.     for index, num in enumerate(arr):
  115.         if index == 0:
  116.             sorted_arr_str += f"{num:3}"  # Add two spaces for single-digit numbers
  117.         else:
  118.             sorted_arr_str += f", {num:3}" if num >= 10 else f",  {num:2}"  # Add one space for two-digit numbers
  119.     sorted_arr_str += "]"
  120.     print("Sorted array:  ", sorted_arr_str)
  121.    
  122.     # Print completion message
  123.     print("\nRadix Sorting Complete!\n\n\tExiting Program...   GoodBye!")
  124.  
  125. if __name__ == "__main__":
  126.     main()
  127.  
  128.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement