python example for quick sort

In this tutorial, you will learn how quick sort work with example.

Quicksort is an efficient in-place sorting algorithm, which usually performs about two to three times faster than merge sort and heapsort when implemented well. Quicksort is a comparison sort, meaning that it can sort items of any type for which a less-than relation is defined. In efficient implementations, it is usually not a stable sort.

Example :

    
# python program to sort array or list using quick sort
def QuickSort(arr):
    el = len(arr)
    
    if el < 2:
        return arr
    
    current_position = 0

    for i in range(1, el):
         if arr[i] <= arr[0]:
              current_position += 1
              temp = arr[i]
              arr[i] = arr[current_position]
              arr[current_position] = temp

    temp = arr[0]
    arr[0] = arr[current_position] 
    arr[current_position] = temp
    
    left = QuickSort(arr[0:current_position])
    right = QuickSort(arr[current_position+1:el])

    arr = left + [arr[current_position]] + right
    
    return arr

arr = [45,22,65,78,9,23,89,52]

print("Before Sorted :: ",arr)
print("After Sorted :: ",QuickSort(arr))
       

Output :

    
Before Sorted ::  [45, 22, 65, 78, 9, 23, 89, 52]
After Sorted ::  [9, 22, 23, 45, 52, 65, 78, 89]
    

Share your thoughts

Ask anything about this examples