Python
Python

 

 

Quick Sort is an efficient sorting algorithm that employs a divide-and-conquer strategy to sort elements in an array or list. It works by selecting a ‘pivot’ element from the array and partitioning the other elements into two sub-arrays according to whether they are less than or greater than the pivot. The sub-arrays are then sorted recursively.

Program Implementation

def quick_sort(arr):
    """Sorts an array using the Quick Sort algorithm.
    
    Args:
        arr (list): The list of elements to be sorted.

    Returns:
        list: The sorted list.
    """
    if len(arr) <= 1:
        return arr  # Base case: arrays with 0 or 1 element are sorted

    pivot = arr[len(arr) // 2]  # Choose the middle element as pivot
    left = [x for x in arr if x < pivot] # Elements less than pivot middle = [x for x in arr if x == pivot] # Elements equal to pivot right = [x for x in arr if x > pivot]  # Elements greater than pivot

    # Recursively apply quick_sort to the left and right partitions
    return quick_sort(left) + middle + quick_sort(right)

# Example usage
if __name__ == "__main__":
    sample_list = [34, 7, 23, 32, 5, 62]
    sorted_list = quick_sort(sample_list)
    print("Sorted list:", sorted_list)

Program Structure Explanation

  • Function Definition: The function quick_sort takes a list arr as input.
  • Base Case: If the list has 0 or 1 element, it is returned as is since it is already sorted.
  • Pivot Selection: The pivot is chosen as the middle element of the list.
  • Partitioning: Three lists are created:
    • left: contains elements less than the pivot.
    • middle: contains elements equal to the pivot.
    • right: contains elements greater than the pivot.
  • Recursive Calls: The function recursively sorts the left and right lists and concatenates them with the middle list to form the sorted result.

Example Output

When running the program with the sample list [34, 7, 23, 32, 5, 62], the output will be:

Sorted list: [5, 7, 23, 32, 34, 62]

 

By Aditya Bhuyan

I work as a cloud specialist. In addition to being an architect and SRE specialist, I work as a cloud engineer and developer. I have assisted my clients in converting their antiquated programmes into contemporary microservices that operate on various cloud computing platforms such as AWS, GCP, Azure, or VMware Tanzu, as well as orchestration systems such as Docker Swarm or Kubernetes. For over twenty years, I have been employed in the IT sector as a Java developer, J2EE architect, scrum master, and instructor. I write about Cloud Native and Cloud often. Bangalore, India is where my family and I call home. I maintain my physical and mental fitness by doing a lot of yoga and meditation.

Leave a Reply

Your email address will not be published. Required fields are marked *

error

Enjoy this blog? Please spread the word :)