Section 15: Searching And Sorting

Exercise 01: Bubble Sort

Date completed: 05/02/2020

Implement bubble sort — another simple yet inefficient sorting technique. It’s called bubble sort or sinking sort because smaller values gradually “bubble” their way to the top of the array (i.e., toward the first element) like air bubbles rising in water, while the larger values sink to the bottom (end) of the array.

The technique uses nested loops to make several passes through the array. Each pass compares successive pairs of elements. If a pair is in increasing order (or the values are equal), the bubble sort leaves the values as they are. If a pair is in decreasing order, the bubble sort swaps their values in the array.

The first pass compares the first two elements of the array and swaps their values if necessary. It then compares the second and third elements in the array. The end of this pass compares the last two elements in the array and swaps them if necessary. After one pass, the largest element will be in the last index. After two passes, the largest two elements will be in the last two indices.

Explain why bubble sort is an O(n2) algorithm.

Big O Notation is a mathematical notation that describes the limiting behavior of a function when the argument tends towards a particular value or infinity. In computer science, big O notation is used to classify algorithms according to how their running time or space requirements grow as the input size grows. Big O notation characterizes functions according to their growth rates: different functions with the same growth rate may be represented using the same O notation.

Bubble sort is a simple, inefficient sorting algorithm used to sort lists. Running time is an important thing to consider when selecting a sorting algorithm since efficiency is often thought of in terms of speed. Bubble sort has an average and worst-case running time of O(n2), so in most cases, a faster algorithm is more desirable.

The Created Code

The source code can be found here. It has been compressed in to a 7-Zip file.

Some screen prints

Description Screen Print Out
Screen print of application after running it in Eclipse. java_s15_ex01 image