{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Implementation of Selection Sort\n", "\n", "The selection sort improves on the bubble sort by making only one exchange for every pass through the list. In order to do this, a selection sort looks for the largest value as it makes a pass and, after completing the pass, places it in the proper location. As with a bubble sort, after the first pass, the largest item is in the correct place. After the second pass, the next largest is in place. This process continues and requires n−1 passes to sort n items, since the final item must be in place after the (n−1) st pass." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Resources for Review\n", "\n", "Check out the resources below for a review of Selection sort!\n", "\n", "* [Wikipedia](https://en.wikipedia.org/wiki/Selection_sort)\n", "* [Visual Algo](http://visualgo.net/sorting.html)\n", "* [Animation](http://cs.armstrong.edu/liang/animation/web/SelectionSort.html)\n", "* [Sorting Algorithms Animcation with Pseudocode](http://www.sorting-algorithms.com/selection-sort)" ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "collapsed": true }, "outputs": [], "source": [ "def selection_sort(arr):\n", " \n", " # For every slot in array\n", " for fillslot in range(len(arr)-1,0,-1):\n", " positionOfMax=0\n", " \n", " # For every set of 0 to fillslot+1\n", " for location in range(1,fillslot+1):\n", " # Set maximum's location\n", " if arr[location]>arr[positionOfMax]:\n", " positionOfMax = location\n", "\n", " temp = arr[fillslot]\n", " arr[fillslot] = arr[positionOfMax]\n", " arr[positionOfMax] = temp" ] }, { "cell_type": "code", "execution_count": 2, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "[2, 3, 5, 6, 7, 8, 12, 21, 40]" ] }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" } ], "source": [ "arr = [3,5,2,7,6,8,12,40,21]\n", "selection_sort(arr)\n", "arr" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Good Job!" ] } ], "metadata": { "kernelspec": { "display_name": "Python 2", "language": "python", "name": "python2" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 2 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython2", "version": "2.7.11" } }, "nbformat": 4, "nbformat_minor": 0 }