• Design and Analysis of Algorithms
• Home

Design and Analysis Bubble Sort

Bubble Sort is an elementary sorting algorithm, which works by repeatedly exchanging adjacent elements, if necessary. When no exchanges are required, the file is sorted.

This is the simplest technique among all sorting algorithms.

Algorithm: Sequential-Bubble-Sort (A)
fori← 1 to length [A] do
for j ← length [A] down-to i +1 do
if A[A] < A[j - 1] then
Exchange A[j] ↔ A[j-1]

Implementation

voidbubbleSort(int numbers[], intarray_size) {
inti, j, temp;
for (i = (array_size - 1); i >= 0; i--)
for (j = 1; j <= i; j++)
if (numbers[j - 1] > numbers[j]) {
temp = numbers[j-1];
numbers[j - 1] = numbers[j];
numbers[j] = temp;
}
}

Analysis

Here, the number of comparisons are

1 + 2 + 3 +...+ (n - 1) = n(n - 1)/2 = O(n2)

Clearly, the graph shows the n2 nature of the bubble sort.

In this algorithm, the number of comparison is irrespective of the data set, i.e. whether the provided input elements are in sorted order or in reverse order or at random.

Memory Requirement

From the algorithm stated above, it is clear that bubble sort does not require extra memory.

Example

Unsorted list:

 5 2 1 4 3 7 6

1st iteration:

5 > 2 swap

 2 5 1 4 3 7 6

5 > 1 swap

 2 1 5 4 3 7 6

5 > 4 swap

 2 1 4 5 3 7 6

5 > 3 swap

 2 1 4 3 5 7 6

5 < 7 no swap

 2 1 4 3 5 7 6

7 > 6 swap

 2 1 4 3 5 6 7

2nd iteration:

2 > 1 swap

 1 2 4 3 5 6 7

2 < 4 no swap

 1 2 4 3 5 6 7

4 > 3 swap

 1 2 3 4 5 6 7

4 < 5 no swap

 1 2 3 4 5 6 7

5 < 6 no swap

 1 2 3 4 5 6 7

There is no change in 3rd, 4th, 5th and 6th iteration.

Finally,

the sorted list is

 1 2 3 4 5 6 7

Useful Video Courses

Video

Compiler Design Online Training

102 Lectures 10 hours

Video

Sequential Circuit Design

30 Lectures 3 hours

Video

Design Patterns Online Training

31 Lectures 4 hours

Video

InDesign Online Training

43 Lectures 1.5 hours

Video

Canva: Become a Graphic Designer

7 Lectures 1 hours

Video

The Ultimate Canva Graphic Design Course

54 Lectures 4 hours