Quick Sort

Quick Sort

Quick Sort is another efficient sorting algorithm that follows the divide-and-conquer approach. It works by selecting a pivot element from the array and partitioning the other elements into two subarrays, according to whether they are less than or greater than the pivot. The subarrays are then recursively sorted, and the sorted subarrays are combined to obtain the final sorted array.

Here's a step-by-step explanation of the Quick Sort algorithm:



The partitioning step involves iterating through the array and moving elements to the left or right side of the pivot based on their values. After the partitioning is complete, the pivot element is in its final sorted position, as all elements to its left are smaller and all elements to its right are greater.

Quick Sort has a time complexity of O(n log n) on average and O(n^2) in the worst case, but it is generally faster than other sorting algorithms like Bubble Sort and Selection Sort. It is also an in-place sorting algorithm, meaning it doesn't require additional memory beyond the initial array.

Quick Sort Code in Python

Here's an example of the Quick Sort algorithm implemented in Python:

def quick_sort(arr):

    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)

# Example usage:

array = [5, 2, 8, 1, 9, 3]

sorted_array = quick_sort(array)

print("Sorted array:", sorted_array)