Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python3
- # -*- coding: utf-8 -*-
- # Filename: quick_sort_demo.py
- # Version: 1.0.0
- # Author: Jeoi Reqi
- """
- Description:
- This script demonstrates the Quick Sort algorithm by sorting an array of integers.
- Requirements:
- - Python 3.x
- Functions:
- - quick_sort(arr):
- Perform quick sort on the given list `arr`.
- Usage:
- - Run the script to see the Quick Sort algorithm in action.
- Example:
- >>> arr = [12, 11, 13, 5, 6, 7]
- >>> sorted_arr = quick_sort(arr)
- >>> print("Sorted array:", sorted_arr)
- Sorted array: [ 5, 6, 7, 11, 12, 13]
- Additional Notes:
- - Quick Sort is an efficient sorting algorithm with a time complexity of O(n log n).
- """
- def quick_sort(arr):
- """
- Perform quick sort on the given list `arr`.
- Args:
- arr (list): List of integers to be sorted.
- Returns:
- list: Sorted list of integers using quick sort.
- """
- if len(arr) <= 1:
- return arr
- pivot = arr[len(arr) // 2]
- left = [x for x in arr if x < pivot]
- middle = [x for x in arr if x == pivot]
- right = [x for x in arr if x > pivot]
- return quick_sort(left) + middle + quick_sort(right)
- def main():
- """
- Main function to demonstrate quick sort.
- It initializes an example array, sorts it using quick_sort function,
- and prints the original and sorted arrays.
- """
- print("\n\t\t:: QUICK 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 quick sort
- sorted_arr = quick_sort(arr)
- # Print the sorted array
- sorted_arr_str = "["
- for index, num in enumerate(sorted_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("\nQuick Sorting Complete!\n\n\tExiting Program... GoodBye!")
- if __name__ == "__main__":
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement