Computer Program Reading Comprehension Project
U of T Computer Program Reading Comprehension Project
Bubble Sort


This exercise provides questions that will help you understand the Bubble Sort algorithm. The program below sorts the elements of an integer array in ascending order.

Download files: BubbleSort.java
Areas: Sorting algorithms.


BubbleSort.java
1public class BubbleSort {
2
3  public static void bubbleSort(double[] list) {
4    boolean sorted = false;
5
6    for (int top = list.length - 1; top > 0 && !sorted; top--) {
7      sorted = true;
8
9      for (int i = 0; i < top; i++) {
10        if (list[i] > list[i+1] ) {
Displaying 10 of 19 lines
View full source


Question 1
What do lines 10 and 12-15 do?
Solution

Question 2
Ignoring line 11, what does the inner loop do?
Solution

Question 3
Assume the array list has the following elements: 8 9 6 1 2 4 5. What will the array arrangement be after the first iteration of the outer for loop?
Solution

Question 4
What is the arrangement after the second iteration of the outer loop?
Solution

Question 5
What is the purpose of the boolean variable sorted?
Solution

Question 6
How do we change the code to sort the array in descending order?
Solution