lab8-kgashok.py

Table of Contents

Lab 8: Sorting

Sort the given list using selection sort and insertion sort.

[TOC]

Select vs Insert vs Merge vs Quick

  • In selectsort, the position of the update is pre-determined, starting from the end of the list. We then go select the maximum value among the unsorted elements of the list, and swap it with the element in the pre-determined location.

  • In insertsort, given a key, a copy of a pre-determined element in the list, we insert it at the appropriate location after comparing it with the unsorted elements of the list.

  • In mergesort, a divide-and-conquer partitioning algorithm (which more often requires extra memory), the input array is divided in two halves, calls itself recursively for the two halves and then merges the two sorted halves. The merge() function is used for merging two halves.

  • In quicksort, also a divide-and-conquer partitioning algorithm (lends itself to be efficiently implemented in-place without extra memory), the choice of the pivot element determines how the elements get partitioned, and calls itself recursively for the two partitions.

Solution Key

English-like sorting code

index-based insert sort

First see the video and then code! http://j.mp/insertSortVideo

Pythonic versions

  • http://interactivepython.org/runestone/static/pythonds/SortSearch/TheInsertionSort.html

  • http://interactivepython.org/runestone/static/pythonds/SortSearch/TheSelectionSort.html

  • http://bit.ly/insertVisualizer - insertSort in the visualizer

3-problem series for learning/teaching insertsort

  • Part 1- https://www.hackerrank.com/challenges/insertionsort1

  • Part 2 - https://www.hackerrank.com/challenges/insertionsort2

  • Part 3 - https://www.hackerrank.com/challenges/correctness-invariant (fix the bug)

Recursive SelectionSort

Credits: https://code.activestate.com/recipes/576917-functional-selection-sort/#c1

Output

Visualize a slight variant of this code at https://tinyurl.com/x697cwwjarrow-up-right

Recursive InsertionSort

Output

Recursive QuickSort

http://mcsp.wartburg.edu/zelle/python/sigcse-workshop/mgp00064.html

or

or using lambda and filter

and the most efficient:

Improved version of lambda code (without using filter):

http://bit.ly/quickSortVideoCD - a video explaining QuickSort incrementally in a CyberDojo session.

Recursive MergeSort (in-place)

Unit test file

Recursive QuickSort, in-place

http://bit.ly/quickSortVideo

What exactly does this accomplish?

Read the analysis here - http://j.mp/sleepSortGeek

Last updated