Understanding Bubble Sorting

All sorting algorithms accept a list of elements and return them ordered. The main difference between each algorithm is the manner in which the sorting is done. Bubble sorting works by swapping adjacent elements. This pushes the sorted elements toward the end of the list.

Snippet 2.1 shows the pseudocode for bubble sort. The algorithm involves three simple tasks, which involves repeatedly stepping through the list to sort, comparing adjacent elements, and swapping them around if the first element is bigger than the second.

How many passes do we need to perform on the array until our list is sorted? It turns out that to guarantee that our list is sorted, we need to do (n - 1) passes on the list, n being the length of our array. We will show why (n - 1) passes are needed in the next section, but this is the main reason why bubble sort has a runtime complexity of O(n2), since we're processing n elements for n - 1 times.

The pseudocode for bubble sort is as follows:

bubbleSort(array)
n = length(array)
for (k = 1 until n)
for (j = 0 until -1)
if(array[j] > array[j + 1])
swap(array, j, j + 1)
Snippet 2.1: Bubble sort pseudocode

The swap function in the Snippet 2.1 switches the values of the two array pointers j and j+1 using a temporary variable.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.17.81.201