Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
June 24, 2021 08:45 pm GMT

Quick sort algorithm

Definition of quicksort

Quicksort is a type of Divide and Conquer algorithm like merge sort, it works by choosing an element as a pivot from the giving array, and appending the greater elements to the selected pivot, and shifting the smaller elements before it.

Time and Space complexity

The space complexity of quicksort is O(log n)

best-caseaverage caseworst-case
O(n log n)O(n log n)O(n^2) when the list is already sorted, or the pivot is min or max value of the giving list

Implementation of quick sort using python

def QuickSortAlgorithm(arr: list) -> list:    """        [ name ] => Quick Sort        [ type ] => Sorting algorithms        [ time complexity ] => (            1. best case:  O(n log n)            2. average case: O(n log n)            3. worst case: O(n^2) { when the pivot is the (min or max) value of the giving list, or the list is already sorted }        )        [ space complexity ] => O(log n)        [params] => (            arr {list} list to sort        )        [return] => {list} sorted list     """    # size of array    n = len(arr)    if n <= 1:        return arr    # pivote = arr[mid]     pivot = arr[n // 2]    smallerThanPivot = []    greaterThanPivot = []    for i in range(len(arr)):        # do not append pivot to (greaterThanPivot) => continue        if arr[i] == pivot:            continue        # if the element is greater than or equal pivot        if arr[i] >= pivot:            # append the element that is greater than pivot to greaterThanPivot array            greaterThanPivot.append(arr[i])        else:            # if the element is smaller than pivot append it to smallerThanPivot            smallerThanPivot.append(arr[i])    return QuickSortAlgorithm(smallerThanPivot) + [pivot] + QuickSortAlgorithm(greaterThanPivot)

References and useful resources


Original Link: https://dev.to/ayabouchiha/quick-sort-algorithm-1k72

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To