Understanding bubble sort

Bubble sort is the most commonly used sorting algorithm in the programming world. Most of the programmers start learning about sorting with this algorithm. It is a comparison-based sorting algorithm, which is always referred to as one of the most inefficient sorting algorithms. It requires maximum number of comparisons, and the average, and worst case complexity are the same.

In bubble sort, each item of the list is compared with the rest of the items and swapped if required. This continues for each item in the list. We can sort either in ascending or descending order. Here is the pseudo algorithm for bubble sort:

procedure bubbleSort( A : list of sortable items ) 
n = length(A)
for i = 0 to n inclusive do
for j = 0 to n-1 inclusive do
if A[j] > A[j+1] then
swap( A[j], A[j+1] )
end if
end for
end for
end procedure

As we can see from the preceding pseudocode, we are running one loop to ensure that we iterate each item of the list. The inner loop ensures that, once we point to an item, we are comparing the item with other items in the list. Based on our preference, we can swap the two items. The following image shows a single iteration to sort one item of the list. Let's assume our list has the following items: 20, 45, 93, 67, 10, 97, 52, 88, 33, 92. For the first pass (iteration) to sort out the first item, the following steps will be taken:

If we check the preceding image, we can see that we are comparing two numbers and then deciding whether we are going to swap/exchange the item. The items with background color shows the two items we are comparing. As we can see, the first iteration of the outer loop causes the topmost items to be stored in the topmost places in the list. This will continue until we iterate through each of the items in the list.

Let's now implement the bubble sort algorithm using PHP.

..................Content has been hidden....................

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