Merge Sort

Problem statement

Write a python program to sort the given list using mergesort algorithm

Examples:
Input:[5,8,2]
Output:[2,5,8]

Input:[6,2,8,4,3,7,5,1]
Output:[1,2,3,4,5,6,7,8]

Input=[6,-2,8,4,-3,7,-5,1]
Output=[-5,-3,-2,1,4,6,7,8]

Input=[6,-2,"8.8",4.4,-3,7.5,-5,1]
Output="Invalid input"

Input=23
Output="Invalid input"

How it works

Merge sort example

Animation - https://visualgo.net/en/sorting?slide=10 slides - http://bit.ly/KG_mergesort

Pseudo code

Solution key

Pre-Lab Questions

  1. How do you get the number of elements in the list

  2. Merge two lists [2,4,3] and [7,5,6]

  3. Consider left and right lists of size 1. Merge them in a sorted order.

  1. Now consider the two sorted lists of unspecified size. Merge them in a sorted order.

4b. Merge two sorted lists [2,6,7] and [3,5,8] in the sorted order

  1. Divide the list num into left and right halves.

  1. Recursively divide, till the partition size is 1

  1. What are the first two elements to be merged from the input list [6,2,8,4,3,7,5,1] in the mergesort

  2. Validate whether given input is of list type.

  3. Validate whether all the elements in the input are of int type.

  4. Validate whether given list is empty

Post-Lab Questions

  1. Modify the program to validate whether given input is a valid list.

  2. Modify the code to sort the list of string elements.

Bonus

  1. What is the worst case complexity for merge sort algorithm?

Interview Grade

  1. Why quicksort is better than mergesort?

  2. Is there a way to implement a hybrid sort (which uses MergeSort and InsertionSort)? What is the algorithm for this? Clue: Dynamic Task Parallelism https://msdn.microsoft.com/en-us/library/ff963551.aspx

CyberDojo session

  • CD extrenal Link : http://cyberdojo1.kgfsl.com/kata/edit/B006BC6DA0?avatar=bee

  • CD local Link : http://10.100.8.8/kata/edit/B006BC6DA0?avatar=bee

Test cases

Answer key for validating the input

Last updated