Introduction
Bubble Sort is a basic comparison sort algorithm that repeatedly traverses a list, compares adjacent elements and swaps them if they are in the wrong order. When used in a 2D array (matrix), you can employ Bubble Sort in various manners depending on the intent to sort each row separately, or sort the matrix as a complete list of elements.
This guide shows both approaches with examples, pseudocode, and ready-to-run Python and C

Two common approaches
1. Sort each row independently
Sort every row in the matrix using Bubble Sort. Useful when rows represent independent lists (e.g., per-user scores).
Idea: For each row, apply normal 1D Bubble Sort.
Pseudocode:
for each row r in matrix:
for i from 0 to cols-2:
for j from 0 to cols-2-i:
if r[j] > r[j+1]:
swap r[j], r[j+1]
Example:
Input:
[ [3, 1, 2],
[9, 5, 6] ]
After sorting each row:
[ [1, 2, 3],
[5, 6, 9] ]
2. Sort the whole matrix (global sort)
Treat the matrix as a flattened array, sort all elements, then write them back in row-major order. Use this when you want the entire matrix elements globally ordered.
Idea: Flatten → Bubble Sort → Refill matrix.
Pseudocode:
flatten = []
for each row in matrix:
append all elements to flatten
// Apply bubble sort to flatten
for i from 0 to n-2:
for j from 0 to n-2-i:
if flatten[j] > flatten[j+1]:
swap flatten[j], flatten[j+1]
// refill matrix row-major
k = 0
for r from 0 to rows-1:
for c from 0 to cols-1:
matrix[r][c] = flatten[k]
k += 1
Example:
Input:
[ [3, 1, 2],
[9, 5, 6] ]
Flattened: [3,1,2,9,5,6]
→ Sorted: [1,2,3,5,6,9]
→ Matrix
[ [1, 2, 3],
[5, 6, 9] ]
Time & Space Complexity
- Sorting each row: For
r
rows andc
columns, bubble sort per row is O(r * c²). Space O(1) extra. - Sorting entire matrix: For
n = r*c
elements, Bubble Sort is O(n²) = O((r*c)²). Space O(1) extra if your algorithm swaps in-place after flattening into an array; flattening may need O(n) auxiliary space if you create a new list.
Bubble Sort is simple but inefficient for large data. Use it for teaching, small inputs, or where stability and simplicity matter more than speed.
When to use which approach?
- Sort each row when rows represent independent lists (per-user logs, per-row priorities).
- Sort entire matrix when you need global ordering across all elements (e.g., prepare a matrix for binary search over flattened data).
- For large matrices choose faster algorithms (Quick-Sort, Merge-Sort, or built-in sorts) rather than Bubble Sort.
Conclusion:
Bubble Sort on 2D Arrays – Key Points
- Two main approaches:
- Apply Bubble Sort row by row.
- Flatten the 2D array into a 1D array, sort it, then reshape back.
- Simplicity: Both approaches are straightforward and great for beginners.
- Time Complexity: Runs in O(n²), making it inefficient for large datasets.
- Use Case: Best suited for small inputs, learning, and demonstrations.
- Alternative: For bigger datasets, prefer faster algorithms like Merge Sort, Quick Sort, or built-in sort functions.