4.15 Sorting Algorithms
From CS Awesome 2CC BY-NC-SA 4.0Original page
Java2 class periods2 exercisesNot autograded
Files
4.15 Sorting Algorithms
Each coding exercise has its own folder. Open its .java file and press Run to try it.
There are many sorting algorithms to put an array or ArrayList elements in alphabetic or numerical order. Selection sort and insertion sort are iterative sorting algorithms that can be used to sort elements in an array or ArrayList. We will show these algorithms below for arrays. The three sorting algorithms that you need to know for the AP CSA exam are:
- Selection sort repeatedly selects the smallest (or largest) element from the unsorted portion of the list and swaps it into its correct (and final) position in the sorted portion of the list.
- Insertion sort inserts an element from the unsorted portion of a list into its correct (but not necessarily final) position in the sorted portion of the list by shifting elements of the sorted portion to make room for the new element.
- Merge sort breaks the elements into two parts and recursively sort each part. An array of one item is sorted (base case). Then merge the two sorted arrays into one. MergeSort will be covered in lesson 4.17.
Selection Sort
Selection sort usually starts at index 0 and looks through the entire array keeping track of the index of the smallest value in the array (a findMin algorithm) and then swaps the value at the smallest index with the value at index 0. Then it does the same thing for index 1, then 2, and so on until it reaches the length of the array minus one. At this point the array is sorted in ascending order.
Here is a folk dance video that shows the selection sort process.
And a short video that describes how selection sort works.
To identify a selection sort look for the following:
- a nested for loop with the outer loop starting at 0 and ending when the index reaches length - 1 (see line 7 below)
- the index of the smallest value should start at the outer loop index (see line 9 below)
- the inner loop should start at the outer loop index + 1 and loop through the whole array (see line 10 below)
- if the value in the array at the index of the inner loop is less than the value at the smallest index then set the smallest index to the index of the inner loop (see lines 12 - 15)
- swap the value at the outer loop index and the smallest value (the one at the smallest value index) (see lines 17-19)
The code for selectionSort below is from the AP CSA course description.
Exercise 1
Demonstration of selection sort.
Open the
01-selSortfolder and runSortTest.java. It is an example, so it has no tests.
To see this executing using the Java Visualizer click on the following SelectionSort
Check your understanding: Under what condition will a selection sort execute faster? — answer it on CS Awesome: https://runestone.academy/ns/books/published/csawesome2/topic-4-15-sorting.html#qsel_1
Check your understanding: This method should sort the numbers in the passed array into ascending order. But, it does not work. Which of the following lines is wrong?
public static void selectionSort(int[] elements) { for (int j = 0; j < elements.length − 1; j++) // line 1 { int minIndex = j; // line 2 for (int k = 0; k < elements.length; k++) // line 3 { if (elements[k] < elements[minIndex]) // line 4 { minIndex = k; // line 5 } } int temp = elements[j]; elements[j] = elements[minIndex]; elements[minIndex] = temp; } }Answer it on CS Awesome: https://runestone.academy/ns/books/published/csawesome2/topic-4-15-sorting.html#qsel_2
You can step through the code above by clicking on the following Ex-12-4-2.
Insertion Sort
Insertion sort usually starts at index 1 and inserts the value at index 1 into its correct place in the already sorted part (the part to the left of the current index). It moves any value larger than the value stored in temp to the right until it either finds the appropriate place to put temp or gets to the front of the array.
Here is a folk dance video that shows the insertion sort process.
And a short video that describes how insertion sort works.
To identify an insertion sort look for the following:
- an outer for loop that starts at 1 and loops through the entire array (see line 7)
- storing the element value at the outer loop index in temp (see line 9)
- setting the possible index to the outer loop index (see line 10)
- an inner while loop that loops while the possible index is greater than 0 and the value in temp is less than the value at the possible index minus one (see line 11)
- set the value at the possible index to the one to the left of it (the one at possible index minus one) (see line 13)
- decrement the possible index (subtract one from it) (see line 14)
- when the while loop ends set the value at the possible index to temp (see line 16)
The code for insertionSort below is from the AP CSA course description.
Exercise 2
Demonstration of insertion sort.
Open the
02-insertionSortfolder and runSortTest.java. It is an example, so it has no tests.
To see this executing using the Java Visualizer click on the following Insertion-Sort
Check your understanding: Under what condition will an insertion sort execute faster? — answer it on CS Awesome: https://runestone.academy/ns/books/published/csawesome2/topic-4-15-sorting.html#qins_1
Check your understanding: This method should sort the numbers in the passed array into ascending order. But, it does not work. Which of the following lines is wrong?
public static void insertionSort(int[] elements) { for (int j = 1; j < elements.length - 1; j++) // line 1 { int temp = elements[j]; // line 2 int possibleIndex = j; // line 3 while (possibleIndex > 0 && temp < elements[possibleIndex - 1]) // line 4 { elements[possibleIndex] = elements[possibleIndex - 1]; // line 5 possibleIndex--; } elements[possibleIndex] = temp; } }Answer it on CS Awesome: https://runestone.academy/ns/books/published/csawesome2/topic-4-15-sorting.html#qins_2
You can step through the code above by clicking on the following Visualization.
Coding Challenge: Sort Runtimes
Selection sort and Insertion sort have similar runtimes. They both have nested loops that run through the data of size n approximately n squared times. However, they perform differently on some data.
In the exercises for Selection sort and Insertion sort above, add in a counter and increment it inside the inner loop to count the number of iterations. Add in print statements that will print the counter value after the loops. Run the code on the following data and record the runtimes in this Google document (login to Google to make your own copy) also seen below.
Open it on CS Awesome: https://runestone.academy/ns/books/published/csawesome2/topic-4-15-sorting.html#coding-challenge-sort-runtimes
Compare the runtimes of selection and insertion sort on the same data. There should be some data where one performed better than the other. Can you explain why this is? Trace through the code to figure out why. Discuss in pairs or groups. Using the space provided below, summarize the key discussion points and include a link to your Google document with the table of runtimes.
Discuss this with your class, or answer it on CS Awesome: https://runestone.academy/ns/books/published/csawesome2/topic-4-15-sorting.html#challenge-sorting
Summary
- (AP 4.15.A.1) Selection sort and insertion sort are iterative sorting algorithms that can be used to sort elements in an array or
ArrayList. - (AP 4.15.A.2) Selection sort repeatedly selects the smallest (or largest) element from the unsorted portion of the list and swaps it into its correct (and final) position in the sorted portion of the list.
- (AP 4.15.A.3) Insertion sort inserts an element from the unsorted portion of a list into its correct (but not necessarily final) position in the sorted portion of the list by shifting elements of the sorted portion to make room for the new element.
- Informal run-time comparisons of program code segments can be made using statement execution counts.
Search/Sort Multiple-Choice Exercises
Try the following multiple-choice exercises to practice search and sort algorithms: Search/Sort Multiple-Choice Exercises.
For teachers
4.15 Sorting Algorithms
Students read CSAwesome2's “Sorting Algorithms” in CS Room and work through its 2 Java coding exercises (examples, not graded).
- Time: 2 class periods
- Tests: none
Goals
- (AP 4.15.A.1) Selection sort and insertion sort are iterative sorting algorithms that can be used to sort elements in an array or
ArrayList. - (AP 4.15.A.2) Selection sort repeatedly selects the smallest (or largest) element from the unsorted portion of the list and swaps it into its correct (and final) position in the sorted portion of the list.
- (AP 4.15.A.3) Insertion sort inserts an element from the unsorted portion of a list into its correct (but not necessarily final) position in the sorted portion of the list by shifting elements of the sorted portion to make room for the new element.
Before class
- Import the lesson into your class from the Lessons page, or with New assignment → Use a lesson. It arrives as a draft.
- Publish it.
- The original page, with its free-response and multiple-choice questions, is on CS Awesome: https://runestone.academy/ns/books/published/csawesome2/topic-4-15-sorting.html
- CS Awesome's own teacher materials: the CS Awesome teacher site
In class
- Students read
README.md. Questions that need CS Awesome's interactive widgets link back to it. - Students run the examples in exercises 01–02, each in its own folder.
Exercises
| Folder | File | Grading | Tests |
|---|---|---|---|
01-selSort | SortTest.java | Example, not graded | 0 |
02-insertionSort | SortTest.java | Example, not graded | 0 |