{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Implementation of a Bubble Sort\n", "\n", "The bubble sort makes multiple passes through a list. It compares adjacent items and exchanges those that are out of order. Each pass through the list places the next largest value in its proper place. In essence, each item “bubbles” up to the location where it belongs." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Resources for Review\n", "\n", "Check out the resources below for a review of Bubble sort!\n", "\n", "* [Wikipedia](https://en.wikipedia.org/wiki/Bubble_sort)\n", "* [Visual Algo](http://visualgo.net/sorting.html)\n", "* [Animation](http://www.cs.armstrong.edu/liang/animation/web/BubbleSort.html)\n", "* [Sorting Algorithms Animcation with Pseudocode](http://www.sorting-algorithms.com/bubble-sort)" ] }, { "cell_type": "code", "execution_count": 3, "metadata": { "collapsed": true }, "outputs": [], "source": [ "def bubble_sort(arr):\n", " # For every element (arranged backwards)\n", " for n in range(len(arr)-1,0,-1):\n", " #\n", " for k in range(n):\n", " # If we come to a point to switch\n", " if arr[k]>arr[k+1]:\n", " temp = arr[k]\n", " arr[k] = arr[k+1]\n", " arr[k+1] = temp" ] }, { "cell_type": "code", "execution_count": 7, "metadata": { "collapsed": false }, "outputs": [], "source": [ "arr = [3,2,13,4,6,5,7,8,1,20]\n", "bubble_sort(arr)" ] }, { "cell_type": "code", "execution_count": 8, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "[1, 2, 3, 4, 5, 6, 7, 8, 13, 20]" ] }, "execution_count": 8, "metadata": {}, "output_type": "execute_result" } ], "source": [ "arr" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Great 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 }