Skip to main content

Python Quick Sort

Here you get python quick sort program and algorithm.

Quick sort is based on divide and Conquer technique. We divide our array into sub-arrays and that sub-arrays divided into another sub-arrays and so on, until we get smaller arrays. Because it is easy to solve small arrays in compare to a large array.

Sorting smaller arrays will sort the entire array.

Python Quick Sort

To understand Quick Sort let’s  take an example:-

Example

We have an array [48,44,19,59,72,80,42,65,82,8,95,68]

First of all we take first element and place it at its proper place. We call this element Pivot element.

Note: We can take any element as Pivot element but for convenience the first element is taken as Pivot.

There are two condition to place Pivot at its proper place.

  • All the elements to the left of Pivot element should be smaller than
  • All the elements to the right of Pivot element should be greater than

In given array, we’ll take first element as Pivot element which is 48. Now place it at its proper place according to first two conditions.

Python Quick Sort 1

Here all the elements to the left is smaller and to right are greater than Pivot.

If you confused that how we placed Pivot at its proper place then wait we’ll discuss it later in partition algorithm.

Well, now we’ll take two sub-lists/sub-arrays left and right of our Pivot element (48).  Sub-lists will be

[42,44,19,8] and [80,72,65,82,59,95,68]

and will also take first element as Pivot element in both and place the their Pivot elements at their proper places using partition algorithm. After this step each of the sub-lists will be divided into two parts then new sub-lists will be divided into another two parts and so on until we reached the end.

Let’s see how it will look like.

Python Quick Sort 2

Pivot element represented by Green color.

We can write a recursive function for this procedure. There would be two terminating conditions. When the sub-list has only 1 element or when no sub-list is formed. If the value of low is equal to up then there will be only one element in the sub-list and if the value of low exceeds up then no sub-list is formed. So our algorithm will be.

Algorithm

Quick[array, low,up]

Where low and up are lower and upper bound of the array.

STEP 1:    if low>=up then return

STEP 2:    set piv_loc = call partition(array,low,up)

                   [calling partition to find the location of pivot]

STEP 3:    call Quick(array,low,piv_loc-1)

                        [Calling Quick for left sub-list]

STEP 4:    call Quick(array,piv_loc+1, up)

                        [Calling Quick for right sub-list]

Partition [array, low, up]

This algorithm is to find the location of pivot element and return it.

STEP 1:  set i = low+1

Set j = up

Set pivot = array[low]

STEP 2:  while(i <= j)

{

While(( array[i] < pivot ) and ( i < up ))

Increase i by 1

While ( array[j] > pivot )

Decrease j by 1

If ( i < j )

{

Swap the value of array[i] with array[j]

Increase i by 1

Decrease j by 1

}

Else

Increase i by 1

}

STEP 3:    set array[low] = array[j]

Set array[j] = pivot

Return j

Time Complexity

Best Case: O (n log2n)

Average Case: O (n log n)

Worst Case: O (n2)

Program for Quick Sort in Python

Array = [48,44,19,59,72,80,42,65,82,8,95,68]
low = 0
up = len(Array) - 1

def partition(Array,low,up):
        i = low+1
        j = up
        pivot = Array[low]
        while(i<=j):
                while(Array[i]<pivot and i<up):
                        i = i+1
                while(Array[j]>pivot):
                        j = j-1
                if(i<j):
                        Array[i],Array[j] = Array[j],Array[i]
                        i = i+1
                        j = j-1
                else:
                        i = i+1
        Array[low] = Array[j]
        Array[j] = pivot
        return j

def quick(Array,low,up):
        if(low>=up):
                return
        piv_loc = partition(Array,low,up)
        quick(Array,low,piv_loc-1)
        quick(Array,piv_loc+1,up)

quick(Array,low,up)

for i in Array:
        print i,

Output

8 19 42 44 48 59 65 68 72 80 82 95

Comment below if you have doubts related to above python quicksort tutorial.

The post Python Quick Sort appeared first on The Crazy Programmer.



from The Crazy Programmer https://www.thecrazyprogrammer.com/2017/12/python-quick-sort.html

Comments

Popular posts from this blog

dotnet sdk list and dotnet sdk latest

Can someone make .NET Core better with a simple global command? Fanie Reynders did and he did it in a simple and elegant way. I'm envious, in fact, because I spec'ed this exact thing out in a meeting a few months ago but I could have just done it like he did and I would have used fewer keystrokes! Last year when .NET Core was just getting started, there was a "DNVM" helper command that you could use to simplify dealing with multiple versions of the .NET SDK on one machine. Later, rather than 'switching global SDK versions,' switching was simplified to be handled on a folder by folder basis. That meant that if you had a project in a folder with no global.json that pinned the SDK version, your project would use the latest installed version. If you liked, you could create a global.json file and pin your project's folder to a specific version. Great, but I would constantly have to google to remember the format for the global.json file, and I'd constan...

Rail Fence Cipher Program in C and C++[Encryption & Decryption]

Here you will get rail fence cipher program in C and C++ for encryption and decryption. It is a kind of transposition cipher which is also known as zigzag cipher. Below is an example. Here Key = 3. For encryption we write the message diagonally in zigzag form in a matrix having total rows = key and total columns = message length. Then read the matrix row wise horizontally to get encrypted message. Rail Fence Cipher Program in C #include<stdio.h> #include<string.h> void encryptMsg(char msg[], int key){ int msgLen = strlen(msg), i, j, k = -1, row = 0, col = 0; char railMatrix[key][msgLen]; for(i = 0; i < key; ++i) for(j = 0; j < msgLen; ++j) railMatrix[i][j] = '\n'; for(i = 0; i < msgLen; ++i){ railMatrix[row][col++] = msg[i]; if(row == 0 || row == key-1) k= k * (-1); row = row + k; } printf("\nEncrypted Message: "); for(i = 0; i < key; ++i) f...

Data Encryption Standard (DES) Algorithm

Data Encryption Standard is a symmetric-key algorithm for the encrypting the data. It comes under block cipher algorithm which follows Feistel structure. Here is the block diagram of Data Encryption Standard. Fig1: DES Algorithm Block Diagram [Image Source: Cryptography and Network Security Principles and Practices 4 th Ed by William Stallings] Explanation for above diagram: Each character of plain text converted into binary format. Every time we take 64 bits from that and give as input to DES algorithm, then it processed through 16 rounds and then converted to cipher text. Initial Permutation: 64 bit plain text goes under initial permutation and then given to round 1. Since initial permutation step receiving 64 bits, it contains an 1×64 matrix which contains numbers from 1 to 64 but in shuffled order. After that, we arrange our original 64 bit text in the order mentioned in that matrix. [You can see the matrix in below code] After initial permutation, 64 bit text passed throug...