0% found this document useful (0 votes)
8 views9 pages

Bubble Sort Example

Uploaded by

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

Bubble Sort Example

Uploaded by

pettagsco
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Bubble Sort — Step by Step

We will sort the list [8, 10, 6, 2, 4] using Bubble Sort.


Each pass compares adjacent pairs and swaps them if out of order.
The largest element 'bubbles' to the end of the list.
Standard Bubble Sort Code
def bubble_sort(arr):
n = len(arr)
for i in range(n):
for j in range(0, n - i - 1):
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
return arr
Example List
Initial list: [8, 10, 6, 2, 4]
Pass 1 Details
Pass 1:
Compare 8 and 10 (indices 0,1) → no swap → [8, 10, 6, 2, 4]
Compare 10 and 6 (indices 1,2) → swap → [8, 6, 10, 2, 4]
Compare 10 and 2 (indices 2,3) → swap → [8, 6, 2, 10, 4]
Compare 10 and 4 (indices 3,4) → swap → [8, 6, 2, 4, 10]
Pass 2 Details
Pass 2:
Compare 8 and 6 (indices 0,1) → swap → [6, 8, 2, 4, 10]
Compare 8 and 2 (indices 1,2) → swap → [6, 2, 8, 4, 10]
Compare 8 and 4 (indices 2,3) → swap → [6, 2, 4, 8, 10]
Pass 3 Details
Pass 3:
Compare 6 and 2 (indices 0,1) → swap → [2, 6, 4, 8, 10]
Compare 6 and 4 (indices 1,2) → swap → [2, 4, 6, 8, 10]
Pass 4 Details
Pass 4:
Compare 2 and 4 (indices 0,1) → no swap → [2, 4, 6, 8, 10]
Pass 5 Details
Pass 5:
Result & Notes
Final sorted list: [2, 4, 6, 8, 10]

• Each pass moves the largest remaining element to the end.


• Bubble Sort compares only adjacent pairs.
• Time complexity: O(n²) worst/average.
• Space complexity: O(1).

You might also like