{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Insertion Sort\n", "© 2021, Joe James" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### using for loop" ] }, { "cell_type": "code", "execution_count": 19, "metadata": {}, "outputs": [], "source": [ "def insertion_sort1(A):\n", " for i in range(1, len(A)):\n", " for j in range(i-1, -1, -1):\n", " if A[j] > A[j+1]:\n", " A[j], A[j+1] = A[j+1], A[j]\n", " else:\n", " break" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### using while loop " ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [], "source": [ "def insertion_sort2(A):\n", " for i in range(1, len(A)):\n", " j = i-1\n", " while A[j] > A[j+1] and j >= 0:\n", " A[j], A[j+1] = A[j+1], A[j]\n", " j -= 1" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Test Function\n", "Set a result flag. The j loop is used to perform 1000 test iterations. The next two lines create and shuffle list A of 100 integers. Then A is passed to our sorting function. The sorted result is compared to a sort using Python's sorted function. After 1000 iterations of the test, the result is printed." ] }, { "cell_type": "code", "execution_count": 23, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Success\n", "Success\n" ] } ], "source": [ "import random\n", "\n", "def test(func):\n", " result = 'Success'\n", " for j in range(1000):\n", " A = [k for k in range(100)]\n", " random.shuffle(A)\n", " func(A)\n", " if A != sorted(A):\n", " result = 'Failed'\n", " print(result)\n", "test(insertion_sort1)\n", "test(insertion_sort2)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.7.0" } }, "nbformat": 4, "nbformat_minor": 2 }