Skip to main content

Python Merge Sort

Here you will learn about python merge sort algorithm.

Merge sort is based on divide and conquer technique.

All we have to do is divide our array into 2 parts or sub-arrays and those sub-arrays will be divided into other two equal parts. We will divide the array in this manner until we get single element in each part because single element is already sorted.

After dividing the array into various sub-arrays having single element, now it is the time to conquer or merge them together but in sorted manner.

Python Merge Sort

Example

Let’s see an example:

We have an array  [ 99, 21, 19, 22, 28, 11, 14, 18 ].

Python Merge Sort 1

There are 8 elements in the array. Break it into two equal parts.

Python Merge Sort 2

And repeat breaking until we get single element in each part or sub-array.

Python Merge Sort 3 Python Merge Sort 4

We have single element in each sub-array. Now we have to merge them in the same way as had divided it, but in sorted manner.

Compare 99 with 21, 19 with 22, 28 with 11, 14 with 18 and place the smaller number first (for ascending order).

Python Merge Sort 5

here we have sorted arrays, keep conquering until we get complete sorted array.

Python Merge Sort 6

And finally our array is sorted.

Python Merge Sort 7

This was the theoretical concept, now take a look on how to implement this concept in programming.

First we’ll see an algorithm, in which we’ll divide given array into sub-arrays using recursion.

Second we’ll see algorithm for merging two sub-arrays into a single array but in sorted order.

Algorithm

Mergesort(Array)

Step:1-  set n = length(Array)

If (n<2) then return

Step:2-  set mid = n/2

Initialize array “left” having size (mid)

Initialize array “right” having size (n-mid)

Step:3-  for i = 0 to mid – 1

left [i] = Array[i]

[exit loop]

               for i = mid to n-1

right[i] = Array[i]

[exit loop]

Step:4-  call mergesort(left)

Call mergesort(right)

Call merge(left,right,Array)

merge(left, right, Array)

Step:1 – set i = 0, j =0,  k = 0

[i,j,k will represent the indexes of left,right and Array respectively. ]

Step:2 –   while (i<length(left) and j<length(right)

{

If (left[i] < right[j])

Then set Array[k] = left[i]

Increase i by 1

[end of if statement]

else

Set Array[k] = right[j]

Increase j  by 1

[end of else statement]

Increase  k by 1

[end of while loop]

Step:3- while (i < length(left))

{

Set Array[k] = left[i]

i = i + 1

k = k + 1

}

While (j < length(right))

{

Array[k] = Right[j]

Increase j by 1

Increase k by 1

}

Program for Merge Sort in Python

#array to be sorted
Array = [99,21,19,22,28,11,14,18]

#function for merging two sub-arrays
def merge(left, right, Array):
  i = 0
  j = 0
  k = 0

  while (i<len(left) and j<len(right)):
    if(left[i]<right[j]):
      Array[k] = left[i]
      i = i+1
    else:
      Array[k] = right[j]
      j = j+1

    k = k+1
  
  while(i<len(left)):
    Array[k] = left[i]
    i = i+1
    k = k+1
  
  while(j<len(right)):
    Array[k] = right[j]
    j = j+1
    k = k+1

#function for dividing and calling merge function
def mergesort(Array):
  n = len(Array)
  if(n<2):
    return

  mid = n/2
  left = []
  right = []
  
  for i in range(mid):
    number = Array[i]
    left.append(number)  
   
  for i in range(mid,n):
    number = Array[i]
    right.append(number)

  mergesort(left)
  mergesort(right)

  merge(left,right,Array)
 
#calling mergesort
mergesort(Array)
for i in Array:
  print i,

Output

11 14 18 19 21 22 28 99

Comment below if you have doubts related to about python merge sort tutorial.

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



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

Comments

Popular posts from this blog

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...

Experimental: Reducing the size of .NET Core applications with Mono's Linker

The .NET team has built a linker to reduce the size of .NET Core applications. It is built on top of the excellent and battle-tested mono linker . The Xamarin tools also use this linker so it makes sense to try it out and perhaps use it everywhere! "In trivial cases, the linker can reduce the size of applications by 50%. The size wins may be more favorable or more moderate for larger applications. The linker removes code in your application and dependent libraries that are not reached by any code paths. It is effectively an application-specific dead code analysis ." - Using the .NET IL Linker I recently updated a 15 year old .NET 1.1 application to cross-platform .NET Core 2.0 so I thought I'd try this experimental linker on it and see the results. The linker is a tool one can use to only ship the minimal possible IL code and metadata that a set of programs might require to run as opposed to the full libraries. It is used by the various Xamarin products to extract...