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 listarr
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
andright
lists and concatenates them with themiddle
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]