an introduction to python - sorting

7
An Introduction To Software Development Using Python Spring Semester, 2014 Class #10: Sorting Algorithms

Upload: blue-elephant-consulting

Post on 07-Aug-2015

161 views

Category:

Education


2 download

TRANSCRIPT

Page 1: An Introduction To Python - Sorting

An Introduction To Software Development

Using Python

Spring Semester, 2014

Class #10:Sorting Algorithms

Page 2: An Introduction To Python - Sorting

What Is Sorting?

• Given the list of numbers:9, 2, 7, 0, 5, 8, 1, 4, 3, 6

• Sorting produces:0, 1, 2, 3, 4, 5, 6, 7, 8, 9

• Many, many different ways to sort• The difference is in O(n)

Image Credit: www.coroflot.com

Page 3: An Introduction To Python - Sorting

Bubble Sort

• The algorithm works by comparing each item in the list with the item next to it, and swapping them if required. In other words, the largest element has bubbled to the top of the array. The algorithm repeats this process until it makes a pass all the way through the list without swapping any items.

Image Credit: www.clipartbest.com

Page 4: An Introduction To Python - Sorting

Selection Sort

• The selection sort works as follows: you look through the entire array for the smallest element, once you find it you swap it (the smallest element) with the first element of the array. Then you look for the smallest element in the remaining array (an array without the first element) and swap it with the second element. Then you look for the smallest element in the remaining array (an array without first and second elements) and swap it with the third element, and so on.

Image Credit: www.gograph.com

Page 5: An Introduction To Python - Sorting

Insertion Sort

• To sort unordered list of elements, we remove its entries one at a time and then insert each of them into a sorted part (initially empty)

• In the example, we color a sorted part in green, and an unsorted part in black. Here is an insertion sort step by step. We take an element from unsorted part and compare it with elements in sorted part, moving from right to left.

Image Credit: driverlayer.com

Page 6: An Introduction To Python - Sorting

What We Covered Today

1. Bubble sort

2. Selection sort

3. Insertion sort

Image Credit: http://www.tswdj.com/blog/2011/05/17/the-grooms-checklist/

Page 7: An Introduction To Python - Sorting

What We’ll Be Covering Next Time

1. Lists, Part 2

Image Credit: http://merchantblog.thefind.com/2011/01/merchant-newsletter/resolve-to-take-advantage-of-these-5-e-commerce-trends/attachment/crystal-ball-fullsize/