Bubble Sort Algorithm
Bubble Sort Algorithm
Abstract
This project provides a concise exploration of the Bubble Sort algorithm. It
covers how Bubble Sort works by repeatedly comparing and swapping adjacent
elements to sort a list. The study includes a JavaScript implementation with
detailed explanations, discusses the algorithm's time complexity—highlighting
its O(n 2) worst-case and
O(n) best-case scenarios—and examines key properties like stability,
adaptiveness, and in-place sorting. The findings emphasize Bubble Sort's
simplicity and suitability for educational purposes and small or nearly sorted
datasets.
C2 General
Table of Contents
1. Overview of the Algorithm.........................................................3
1.1 Description....................................................................................3
High-Level Explanation..................................................................................................... 3
Step-by-Step Logic............................................................................................................ 3
JavaScript Example........................................................................................................... 3
Example Walkthrough....................................................................................................... 4
2. Implementation.........................................................................6
2.1 Flowchart......................................................................................6
...........................................................................................................6
...........................................................................................................6
...........................................................................................................6
...........................................................................................................6
2.3 Comments and Explanation.............................................................8
2.4 Edge Cases....................................................................................9
1. Empty Arrays................................................................................................................ 9
2. Arrays with One Element............................................................................................10
3. Arrays with Repeated Elements..................................................................................10
4. Arrays with Negative Numbers....................................................................................11
5. Arrays with Non-Numeric Elements.............................................................................11
3. Complexity Analysis.................................................................13
3.1 Time Complexity...........................................................................13
Worst-Case Time Complexity.......................................................................................... 13
C2 General
4.1.1 Stability.................................................................................................................. 16
4.1.2 Adaptiveness......................................................................................................... 18
4.1.3 In-Place Sorting...................................................................................................... 19
4.1.4 Summary of Properties..........................................................................................19
C2 General
1. Overview of the Algorithm
1.1 Description
High-Level Explanation
Bubble Sort is a straightforward, comparison-based sorting algorithm. It works by repeatedly
stepping through the list to be sorted, comparing each pair of adjacent elements, and
swapping them if they are in the wrong order. This process is repeated until no swaps are
needed, indicating that the list is sorted.
The algorithm gets its name because smaller elements "bubble" to the top (beginning) of
the list, while larger elements "sink" to the bottom (end) with each pass through the list.
Step-by-Step Logic
1. Initialization:
Start with an unsorted array arr of length n.
2. Outer Loop (Passes):
Repeat the following steps for each element in the array (total of n - 1
passes).
3. Inner Loop (Comparisons and Swaps):
For each element from index 0 to n - pass - 1:
o Compare the current element arr[i] with the next element arr[i + 1].
o Swap them if arr[i] > arr[i + 1].
o This moves the largest unsorted element towards the end of the
array.
4. Optimization (Early Termination):
Introduce a swapped flag to monitor if any swaps were made during a pass.
If no swaps occur during a pass, the array is already sorted, and the algorithm
can terminate early.
5. Termination:
The algorithm ends when all elements are sorted in ascending order.
JavaScript Example
Below is a simple implementation of the Bubble Sort algorithm in JavaScript:
C2 General
Example Walkthrough
Let's sort the array [5, 1, 4, 2, 8] step by step using Bubble Sort:
First Pass:
Second Pass:
C2 General
Third Pass:
Limitations
Inefficiency with Large Datasets:
C2 General
Bubble Sort has a time complexity of O(n²) in the average and worst cases,
o
making it impractical for sorting large arrays.
Not Suitable for Performance-Critical Applications:
o Other algorithms like Quick Sort or Merge Sort are significantly more efficient
for larger datasets.
2. Implementation
2.1 Flowchart
Start
i=0
N = length of array
swapped = false
j=0
Yes
i<N No Yes
j<N–i-1
No
Yes Yes
End
temp = arr[j + 1]
arr[j+1] = arr[j]
i++
arr[j] = temp
swapped = true
1. Start
2. Initialize Variables:
Set n as the length of the array.
C2 General
Set i = 0.
3. Outer Loop Condition (i < n):
Yes: Proceed to next step.
No: Go to End.
4. Set swapped = false
5. Set j = 0
6. Inner Loop Condition (j < n - i - 1):
Yes: Proceed to compare elements.
No: Check swapped flag.
7. Compare arr[j] and arr[j + 1]:
If arr[j] > arr[j + 1]:
o Swap arr[j] and arr[j + 1]
o Set swapped = true
Increment j by 1
Loop back to Inner Loop Condition.
8. Check swapped Flag:
If swapped == false:
o Array is sorted. Go to End
Else:
o Increment i by 1
o Loop back to Outer Loop Condition
9. End
C2 General
2.3 Comments and Explanation
Let's break down the code to understand each key step, especially the comparisons, swaps,
and the optimization for early termination.
Function Definition
function bubbleSort(arr) { ... }
o Defines a function bubbleSort that takes an array arr as its parameter.
Variables Initialization
let n = arr.length;
o Stores the length of the array in variable n for easy reference.
Outer Loop
for (let i = 0; i < n; i++) { ... }
o The outer loop runs n times.
o Represents each pass through the array.
o With each pass, the largest unsorted element moves to its correct position at
the end of the array.
C2 General
let swapped = false;
o Initializes a flag swapped as false at the beginning of each pass.
o Used to check if any swaps occurred during the pass.
Inner Loop
for (let j = 0; j < n - i - 1; j++) { ... }
o The inner loop iterates over the unsorted portion of the array.
o n - i - 1 ensures that already sorted elements at the end are not re-evaluated.
Return Statement
return arr;
o Returns the sorted array.
1. Empty Arrays
Scenario:
C2 General
Explanation:
o The length n will be 0, so the outer loop condition i < n fails immediately.
o No iterations occur, and the function returns the empty array as is.
Output:
Explanation:
o The length n is 1.
o The outer loop will run once, but the inner loop condition j < n - i - 1 becomes j
< -1, so it doesn't execute.
o The function returns the array with the single element unchanged.
Output:
C2 General
Explanation:
o The algorithm treats repeated elements like any other elements.
o Comparisons and swaps occur based on the standard comparison operators.
o Equal elements are not swapped, preserving their original order, which makes
Bubble Sort a stable sorting algorithm.
Output:
Explanation:
o The algorithm handles negative numbers correctly since the comparison
operator > works with negative values.
o The sorting process remains the same.
Output:
C2 General
o If the array contains strings or other data types, the comparison logic needs to
be adjusted accordingly.
Handling Strings:
Output
C2 General
3. Complexity Analysis
3.1 Time Complexity
Worst-Case Time Complexity
Bubble Sort has a worst-case time complexity of O(n 2), where n is the number of elements
in the array. This quadratic time complexity arises because, in the worst-case scenario, the
algorithm must perform the maximum number of comparisons and swaps.
Explanation
Number of Passes:
o The outer loop runs n times in the worst case.
Number of Comparisons per Pass:
o On the first pass, the inner loop makes ( n−1 ) comparisons.
o On the second pass, it makes ( n−2 ) comparisons, and so on.
Total Number of Comparisons:
o The total number of comparisons is the sum of the first ( n−1 ) positive
integers:
n ( n−1 )
Total Comparisons = ( n−1 ) + ( n−2 )+ …+1=
2
Time Complexity:
o Since the total number of comparisons is proportional to n2 , the time
complexity is O(n 2)
Pass-by-Pass Analysis:
First Pass:
o Compare 5 and 4 ➔ Swap ➔ [4 , 5 , 3 ,2 , 1]
o Compare 5 and 3 ➔ Swap ➔ [4 , 3 , 5 ,2 , 1]
o Compare 5 and 2 ➔ Swap ➔ [4 , 3 , 2 ,5 , 1]
o Compare 5 and 1 ➔ Swap ➔ [4 , 3 , 2 ,1 , 5]
Second Pass:
o Compare 4 and 3 ➔ Swap ➔ [3 , 4 , 2 ,1 , 5]
o Compare 4 and 2 ➔ Swap ➔ [3 ,2 , 4 ,1 , 5]
o Compare 4 and 1 ➔ Swap ➔ [3 ,2 , 1 , 4 , 5]
Third Pass:
o Compare 3 and 2 ➔ Swap ➔ [2, 3 , 1 , 4 , 5]
o Compare 3 and 1 ➔ Swap ➔ [2, 1 , 3 , 4 , 5]
Fourth Pass:
C2 General
o Compare 2 and 1 ➔ Swap ➔ [1, 2 , 3 , 4 , 5]
Total Swaps: 10
Total Comparisons: 10
In this scenario, the maximum number of swaps and comparisons are made, illustrating the
O(n²) time complexity.
Explanation
Swapped Flag Optimization:
o The swapped flag allows the algorithm to terminate early if no swaps occur
during a pass.
Single Pass:
o The outer loop runs only once because swapped remains false, and the
algorithm breaks out of the loop.
Time Complexity:
o The algorithm performs ( n−1 ) comparisons in one pass, resulting in O(n) time
complexity.
Explanation
Random Order:
o For an array with elements in random order, the algorithm performs
comparisons and swaps that are, on average, proportional to n2 .
Time Complexity:
o Despite the optimization for already sorted arrays, the average performance
remains quadratic.
C2 General
Space Complexity
Bubble Sort has a space complexity of O(1), meaning it requires a constant amount of
additional memory space regardless of the input size.
Explanation
In-Place Sorting:
o The algorithm sorts the array in place, using only a few additional variables (i,
j, swapped, and temp).
Memory Usage:
o Additional space is not dependent on the input size n.
C2 General
Efficiency:
o Quick Sort is significantly more efficient for large datasets.
Use Cases:
o Quick Sort is preferred for performance-critical applications with large
datasets.
o Bubble Sort is suitable for small datasets or educational purposes.
Summary Table
Algorithm Best Time Average Time Worst Time Space Complexity Stable
Bubble Sort 2 2 Yes
O(n) O(n ) O(n ) O(1)
Insertion Sort 2 2 Yes
O(n) O(n ) O(n ) O(1)
Selection Sort 2 2 2 No
O(n ) O(n ) O(n ) O(1)
Quick Sort 2 No
O(n log n) O(n log n) O(n ) O(log n)
Merge Sort Yes
O(n logn) O(n logn) O(n logn) O(n)
Key Takeaways
Efficiency:
o Bubble Sort is inefficient for large datasets due to its quadratic time
complexity.
When to Use Bubble Sort:
o Small datasets where simplicity is more critical than efficiency.
o Educational settings to illustrate basic sorting principles.
o Situations where memory space is extremely limited.
Alternatives:
o For better performance on larger datasets, consider using more efficient
algorithms like Quick Sort or Merge Sort.
C2 General
4. Properties and Key Principles
4.1 Main Properties of Sorting Algorithms
In this section, we will discuss the key properties of the Bubble Sort algorithm, focusing on
its stability, adaptiveness, and in-place sorting characteristic. Understanding these
properties helps in determining the suitability of Bubble Sort for specific applications.
4.1.1 Stability
Definition of Stability
A sorting algorithm is said to be stable if it maintains the relative order of records with equal
keys (values). In other words, two equal elements in the input array remain in the same
order in the sorted output as they were in the input.
Explanation
Comparisons and Swaps:
o Bubble Sort compares adjacent elements and swaps them only if the element
on the left is greater than the one on the right.
o If two elements are equal, no swap is performed, thereby preserving their
original order.
Example:
const items = [
{ value: 3, name: "A" },
{ value: 1, name: "B" },
{ value: 3, name: "C" },
{ value: 2, name: "D" }
];
[
{ value: 1, name: "B" },
{ value: 2, name: "D" },
{ value: 3, name: "A" },
{ value: 3, name: "C" }
];
Observation: The two items with value: 3 ('A' and 'C') maintain their original order.
Significance of Stability
Preserving Data Integrity:
o Stability is crucial when sorting records that have multiple fields. If secondary
fields are important, maintaining the order of equal elements ensures that
information is not lost or misrepresented.
C2 General
Multi-Level Sorting:
o Stable sorting allows for consistent results when sorting on multiple keys
sequentially.
o Example: First sort by last name, then by first name while preserving the
order of last names.
4.1.2 Adaptiveness
Definition of Adaptiveness
A sorting algorithm is said to be adaptive if it takes advantage of existing order in its input.
An adaptive algorithm performs better (i.e., in fewer steps) when the input array is already
partially sorted.
Explanation
Optimized Bubble Sort:
o By introducing a swapped flag, Bubble Sort can detect if the array is already
sorted during a pass.
o If no swaps occur in a pass, the algorithm terminates early.
Performance on Nearly Sorted Arrays:
o The time complexity can approach O(n) when the array is already sorted or
nearly sorted.
Example:
let nearlySortedArray = [1, 2, 3, 5, 4];
Pass 1:
o Swap 5 and 4 ➔ [1, 2, 3, 4, 5]
Pass 2:
o No swaps occur; swapped remains false.
o Algorithm terminates early.
Observation:
The algorithm completes in fewer passes than the worst-case scenario.
Significance of Adaptiveness
Efficiency on Specific Inputs:
o Adaptive algorithms save time on datasets that are already sorted or
partially sorted.
Practical Applications:
o Real-world data often contains ordered sequences; adaptive algorithms
can exploit this to improve performance.
Resource Optimization:
C2 General
o Reduces unnecessary computations, saving processing time and power.
Limitations
Non-Adaptive Without Optimization:
o Without the swapped flag, Bubble Sort is not adaptive and will perform
unnecessary passes even on sorted arrays.
Comparison with Other Adaptive Algorithms:
o While Bubble Sort can be adaptive with optimization, algorithms like Insertion
Sort are inherently more adaptive and efficient on partially sorted data.
Explanation
Memory Usage:
o Bubble Sort operates directly on the input array.
o It uses a fixed number of extra variables (i, j, swapped, temp), regardless of
the array size.
Swapping Mechanism:
o Elements are swapped within the array without the need for auxiliary data
structures.
Space Complexity:
o The algorithm has a space complexity of O(1).
Limitations
Data Type Constraints:
o In-place sorting may not be feasible for data structures that do not allow
efficient element swapping (e.g., linked lists).
C2 General
Stability Trade-Off:
o Some in-place algorithms may sacrifice stability to achieve lower space
complexity, but Bubble Sort maintains both.
Practical Implications
Educational Tools:
o Demonstrates fundamental sorting concepts while highlighting the importance
of algorithmic properties.
Algorithm Selection:
o While Bubble Sort is not the most efficient for large or randomly ordered
datasets, its properties make it a reasonable choice in specific contexts.
Optimization Opportunities:
o Understanding its adaptiveness allows developers to implement optimizations
that can significantly improve performance in suitable scenarios.
C2 General
o Bubble Sort's straightforward logic makes it an excellent example of simple
algorithm design.
Iteration and Comparison:
o Emphasizes the fundamental programming concepts of loops and conditional
statements.
Optimization:
o Demonstrates how minor changes (like the swapped flag) can significantly
impact performance.
Stability: Maintains the relative order of equal elements, making it suitable for sorting
complex data structures.
Adaptiveness: Can be optimized to perform efficiently on nearly sorted datasets,
highlighting the importance of algorithmic optimizations.
In-Place Sorting: Requires minimal additional memory, demonstrating how algorithms
can be designed to be memory-efficient.
Understanding these properties provides insight into the strengths and limitations of Bubble
Sort, reinforcing the importance of selecting the appropriate algorithm based on the specific
needs of the application.
Conclusion
Throughout this project, we have conducted an in-depth exploration of the Bubble Sort
algorithm, covering its mechanics, implementation in JavaScript, complexity analysis, and
key properties. This concluding section summarizes the key insights and reflections on
Bubble Sort's applicability, strengths, and limitations.
C2 General
Summary of Findings
Algorithm Overview
Mechanics: Bubble Sort repeatedly steps through the list, compares adjacent
elements, and swaps them if they are in the wrong order. This process continues until
the list is sorted.
Step-by-Step Logic: The algorithm involves nested loops—the outer loop for passes
and the inner loop for comparisons and swaps. An optimization using a swapped flag
allows for early termination if the list becomes sorted before completing all passes.
Use Cases: Bubble Sort is most effective for educational purposes, small datasets, or
nearly sorted data where its simplicity and adaptiveness can be advantageous.
Implementation Highlights
JavaScript Implementation: Provided a complete and well-commented
implementation of Bubble Sort in JavaScript, emphasizing clarity and readability.
Edge Cases Handling: The implementation gracefully handles empty arrays, single-
element arrays, arrays with repeated elements, and arrays containing negative
numbers or non-numeric data.
Stability and In-Place Sorting: Bubble Sort maintains the relative order of equal
elements (stability) and sorts the array in place without requiring additional memory.
Complexity Analysis
Time Complexity:
o Worst-Case: O(n²), occurring when the array is sorted in reverse order.
o Best-Case: O(n), achievable when the array is already sorted, thanks to the
early termination optimization.
o Average-Case: O(n²), as the algorithm must perform a significant number of
comparisons and swaps on average.
Space Complexity: O(1), since it requires a constant amount of additional memory.
Comparison with Other Algorithms: Bubble Sort is less efficient compared to more
advanced algorithms like Quick Sort (O(n log n)) and Merge Sort (O(n log n)),
especially on large datasets.
C2 General
4. Memory Efficiency: An in-place algorithm that requires only a constant amount of
additional memory (O(1) space complexity).
Final Thoughts
While Bubble Sort is not the most efficient sorting algorithm for general-purpose use,
especially with large datasets, it holds significant value in the realm of computer science
education and specific scenarios where its properties are advantageous. Understanding
Bubble Sort provides a foundation for learning more complex algorithms and appreciating
the trade-offs involved in algorithm design and selection.
In conclusion, Bubble Sort exemplifies how simplicity in algorithm design can offer both
educational benefits and practical applications in certain contexts. Its study enhances our
comprehension of sorting algorithms and prepares us to tackle more complex sorting
challenges with a solid foundational understanding.
C2 General