Initial array
Bubble Sort compares adjacent pairs; larger values bubble toward the right.
C programming · Lesson
Follow adjacent pairs, comparisons, and swaps as larger elements move toward the right.
Bubble Sort compares adjacent elements. If they are out of order it swaps them; after each pass a suffix of the array is already final.
compare v[j],v[j+1] → optional swap → continue → sorted suffix grows
The flowchart keeps algorithm control visible; the Array Lab below makes cells, indices, comparisons, candidates and swaps visible.
Indices stay visible at all times. Sorting traces highlight comparisons, the current candidate, swaps and the region already sorted.
Bubble Sort compares adjacent pairs; larger values bubble toward the right.
5 > 1: swap them.
After the swap: 1, 5.
5 > 4: swap them.
After the swap: 4, 5.
5 > 2: swap them.
After the swap: 2, 5.
5 > 3: swap them.
After the swap: 3, 5.
The largest remaining element is now fixed in its final position on the right.
They are already in the correct order.
4 > 2: swap them.
After the swap: 2, 4.
4 > 3: swap them.
After the swap: 3, 4.
The largest remaining element is now fixed in its final position on the right.
They are already in the correct order.
They are already in the correct order.
The largest remaining element is now fixed in its final position on the right.
They are already in the correct order.
The largest remaining element is now fixed in its final position on the right.
The array is sorted in ascending order.
Run C executes only the example shown on the left, using stdin on the right. The coding challenge below has a separate editor and test button.
1#include <stdio.h>
2
3int main(void)
4{
5 int v[5] = {5, 1, 4, 2, 3};
6 for (int i = 0; i < 4; i = i + 1)
7 {
8 for (int j = 0; j < 4 - i; j = j + 1)
9 {
10 if (v[j] > v[j + 1])
11 {
12 int temp = v[j];
13 v[j] = v[j + 1];
14 v[j + 1] = temp;
15 }
16 }
17 }
18
19 for (int i = 0; i < 5; i = i + 1)
20 printf("%d\n", v[i]);
21 return 0;
22}
Read five integers, perform one full ascending bubble sort pass and print the array.
This is a different program from lab 1. Complete the starter code: Check all test cases compiles this editor and tests every input, including boundary cases.
In the first comparison of {5, 1, 4, 2, 3}, what happens to 5 and 1?
Challenge 1 / 5 · Understanding
Progress: 0 / 5 · correct: 0
ConceptStep separates what is required from what is recommended or useful as reinforcement. Only required prerequisites block your progress.
Relationships: solid line = required · dashed line = recommended · dotted line = reinforcement.