Bubble sort¶
Content summary
This lesson introduces the bubble sort algorithm.
Idea¶
Imagine bubbles rising from the bottom of a glass of water to the surface.
Small bubbles start at the bottom, and as they rise, larger bubbles appear closer to the surface.
If we think of the beginning of the array as the bottom of the water and the end of the array as the surface, we can sort the array by repeatedly letting the larger elements "bubble up" toward the end.
How the insertion sort algorithm works
For i from the first element to the second-to-last element:
-
Traverse the array from index
0up ton - 1 - i(i.e., stop before the lastielements that are already in place), and for each pair of adjacent elementsA[j]andA[j + 1]:- Compare them.
- If
A[j] > A[j + 1], swap them so the larger one moves to the right.
This way:
- After each pass of the inner loop (variable
j), the largest remaining element "bubbles up" to its correct position near the end. - After each full pass of the outer loop (variable
i), the largest element so far is in its final position at the end of the array.
With every new pass of the outer loop, the unsorted portion of the array shrinks by one from the end — because the largest element is now correctly placed.
This is why the algorithm is called bubble sort — the big elements gradually "float" to the top (the end of the array) like bubbles rising in water.
The main idea is illustrated below:
Example illustration¶
Flowchart¶
Visualization¶
Writing the program¶
1. Import the numpy library.
2. Write the function bubble_sort() to implement the bubble sort algorithm.
3. Write the main program.
In the main program, we will not ask the user to input the entire array. Instead, we create a fixed array in the code and then call the bubble_sort() function to sort the array Array.
4. Run the program above. The output will be:
Source code¶
The complete code is available at:
Some English words¶
| Vietnamese | Tiếng Anh |
|---|---|
| hoán vị (hai phần tử) | swap |
| sắp xếp nổi bọt | bubble sort |
| so sánh | compare |