Quick Sort in Python

 Quick Sort in Python

Quick sort is an efficient, recursive divide-and-conquer algorithm for sorting an array. 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, and the sorted sub-arrays are combined to produce the final sorted array.



Here is an example of how you might implement quick sort in Python:

def quick_sort(array):

    if len(array) <= 1:

        return array

    pivot = array[0]

    left = [x for x in array[1:] if x < pivot]

    right = [x for x in array[1:] if x >= pivot]

    return quick_sort(left) + [pivot] + quick_sort(right)


array = [4, 3, 2, 1]

sorted_array = quick_sort(array)

print(sorted_array) # Outputs [1, 2, 3, 4]


In this example, the quick_sort function takes an array as input and returns the sorted array. If the array has fewer than two elements, it is already sorted, so it is returned as-is. Otherwise, the first element is selected as the pivot, and the other elements are partitioned into two sub-arrays according to whether they are less than or greater than the pivot. The left and right lists are created using list comprehensions, which iterate through the array and select the elements that meet the specified criteria. The quick_sort function is then called recursively on the left and right lists, and the sorted sub-arrays are combined with the pivot element to form the final sorted array.

Post a Comment

0 Comments