Quick sort algorithm in python | Python example | Python program



Quick Sort Algorithm in Python.


Quick Sort Algorithm is one of the fastest Sort algorithms.

How Quick Sort algorithm works.

1) First, we take a list.

 7 1 10 2 11

2) Now we take a pivot element(selected any random element or first element or last element), I choose the first element.
    0        1        2        3            4
        7      1 10 2 11
    -5                -4            -3            -2            -1


3) We will choose a 7 as a pivot element Now we will put the element left side who will less than and equal to pivot element(7). And put the element on the right side who is greater than the pivot element(7).

        0            1                2            3                4
2 1       7        11 10
        -5            -4            -3            -2            -1

4)  Now we will cut the list or array into subarray 0 to1 and 3 to 4.

 2 1


 11 10

3) Now repeat this process in two subarrays.
Code until the one element is left.

1       2      7        10 11

4) And you get the result.

1       2      7        10 11

# Python program to sort the array by quicksort.
# First we make a function called arranged.

def arranged(array,start,end):
   
    # Now we can select the first element as pivot number.
    # And select the second element from the left.
    # And select the last element from the right.

    pivot=array[start]
    left=start+1
    right=end
    # Now we can separate the element on the basis of the pivot number.
    # Now we can apply the condition that if the number is less than the pivot number they will be swap to the left side and greater than the pivot number then we will swap the number from the right side.
    while True:
        while left<=right and array[left]<=pivot:
            left+=1
        while left<=right and array[right]>pivot:
            right-=1
    
        # Then we will swap the element
        if right<left:
            break
        else:
            array[left],array[right]=array[right],array[left]
            
    array[start],array[right]=array[right],array[start]
    return right
 
# Now we can cut the array
def part(array,start,end):
    if start<end:
        locked=arranged(array,start,end)   
        part(array,start,locked-1)
        part(array,locked+1,end)
# Now we take the array from the user.
# Now we will find the length of an array.
# Now we will run the part function.
# And, Finally we will print the sorted array.
array=list(map(eval,input("Enter the array:").split()))
al=len(array)
part(array,0,al-1)
print(array)
# Made by Ankur Patel
Output:

If you have a better solution than me, then please share in comment or Email.



Next Post Previous Post
1 Comments
  • Fact-tech
    Fact-tech June 26, 2020 at 1:20 PM

    Nice bro

Add Comment
comment url