{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Lecture 15 - Sorting\n", "\n", "## Overview, Objectives, and Key Terms\n", " \n", "In this lecture and [Lecture 14](A12_Searching.ipynb), we tackle two of the most important practical problems in computing: *searching* and *sorting*. In this lecture, we turn to *sorting*, the more challenging problem and one that was a focus of much research in the early years of computing for making searching easier. We'll flex our knowledge of functions to help write clean and clear sorting programs.\n", "\n", "### Objectives\n", "\n", "By the end of this lesson, you should be able to\n", "\n", "- Sort an array of numbers using brute-force, $\\mathcal{O}(n^2)$ schemes like *selection sort*.\n", "- Sort an array of numbers using divide-and-conquer, $\\mathcal{O}(n\\log n)$ schemes like *merge sort*.\n", "- Apply built-in Python functions to sort sequences.\n", "\n", "### Key Terms\n", "\n", "- selection sort\n", "- stable sorting algorithm (*hint*: see the exercises)\n", "- merge sort\n", "- merge \n", "- divide and conquer" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Sorting is Hard Work\n", "\n", "Sorting a sequence of randomly arranged items is no easy task, often resulting in a lot of repetive motions and paper cuts (if the items are, e.g., student exams). However, computers are great for such repetition, and they don't seem to suffer those paper cuts. The question is: *how to sort*? Sorting, it turns out, presents a rich opportunity for integrating much of the material covered so far.\n", "\n", "The simplest sorting algorithm is based on brute force and leverages the solution to a problem encountered as early as [Lecture 5](A01_Algorithms_Flowcharts_and_Pseudocode.ipynb): finding the minimum value of a sequence of numbers. The basic idea is simple. Given a sequence of $n$ numbers to sort in increasing order, we \n", "\n", "1. Find the smallest value (just as we have previously done).\n", "2. Swap it with the first element in the sequence.\n", "3. Repeat steps (1) and (2) for the last $n-1$ items in the sequence.\n", "\n", "This algorithm is known as [selection sort](https://en.wikipedia.org/wiki/Selection_sort). In more detailed pseudocode, **selection sort** can be written as" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "```\n", "'''The selection sort algorithm to sort an array'''\n", "Input: a, n # sequence of numbers and its length\n", "# Loop through each element a[i] \n", "Set i = 0\n", "While i < n do\n", " # Find the location k of the smallest element after a[i]\n", " Set j = i + 1\n", " Set k = i\n", " While j < n do\n", " If a[j] < a[k] then\n", " Set k = j\n", " Set j = j + 1\n", " # Switch the values of a[i] and a[k], putting them in order\n", " Swap a[i] and a[k]\n", " i = i + 1\n", "```" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Take some time and digest this algorithm. Then try the following exercises:\n", "\n", "