0% found this document useful (0 votes)
4 views2 pages

Bubble Sort

Uploaded by

KhOa Lê
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views2 pages

Bubble Sort

Uploaded by

KhOa Lê
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

Bubble Sort is a simple sorting algorithm.

Here's how it works in basic terms:

1. Start with the first element in a list.


2. Compare each pair of adjacent elements. If the element on the left is bigger than the one on
the right, swap them.
3. Move one step to the right and repeat the comparison and swap if needed.
4. After one full pass through the list, the largest element will be at the end, in its correct
position.
5. Repeat the process for the remaining elements, ignoring the sorted ones at the end.
6. Continue until no more swaps are needed, meaning the list is fully sorted.

Each pass "bubbles up" the largest unsorted element to its correct position, hence the name
"Bubble Sort."

Let’s go through a basic demo of Bubble Sort with a simple list of numbers:

List: [5, 2, 9, 1, 5]

We’ll go through the list step-by-step.

Step-by-Step

1. First Pass:
- Compare `5` and `2`: `5` is bigger, so swap them → `[2, 5, 9, 1, 5]`
- Compare `5` and `9`: `5` is not bigger, so no swap
- Compare `9` and `1`: `9` is bigger, so swap them → `[2, 5, 1, 9, 5]`
- Compare `9` and `5`: `9` is bigger, so swap them → `[2, 5, 1, 5, 9]`

Now, the largest element (`9`) is in the correct position at the end.

2. Second Pass:
- Compare `2` and `5`: `2` is not bigger, so no swap
- Compare `5` and `1`: `5` is bigger, so swap them → `[2, 1, 5, 5, 9]`
- Compare `5` and `5`: They are equal, so no swap

Now, the second-largest element (`5`) is in its correct position.

3. Third Pass:
- Compare `2` and `1`: `2` is bigger, so swap them → `[1, 2, 5, 5, 9]`
- Compare `2` and `5`: `2` is not bigger, so no swap

Now, the list is sorted: `[1, 2, 5, 5, 9]`

After a few passes, every element has "bubbled up" to its correct position!

You might also like