Lists in Python — Question 36
Back to all questionsInsertion Sort
list = [12, 14, -54, 64, 90, 24]
First pass
[12, 14, -54, 64, 90, 24] → [12, 14, -54, 64, 90, 24] — it will not swap since 12 < 14
Second pass
[12, 14, -54, 64, 90, 24] → [12, -54, 14, 64, 90, 24] — it will swap since -54 < 14
[12, -54, 14, 64, 90, 24] → [-54, 12, 14, 64, 90, 24] — it will swap since -54 < 12
Third pass
[-54, 12, 14, 64, 90, 24] → [-54, 12, 14, 64, 90, 24] — it will not swap since 64 > 14
Fourth pass
[-54, 12, 14, 64, 90, 24] → [-54, 12, 14, 64, 90, 24] — it will not swap since 90 > 64
After the fourth pass of insertion sort, the list is: [-54, 12, 14, 64, 90, 24]
Bubble Sort
list = [12, 14, -54, 64, 90, 24]
First pass — [12, -54, 14, 64, 24, 90]
Second pass — [-54, 12, 14, 24, 64, 90]
First pass
[12, 14, -54, 64, 90, 24] → [12, 14, -54, 64, 90, 24] — it will not swap since 12 < 14
[12, 14, -54, 64, 90, 24] → [12, -54, 14, 64, 90, 24] — it will swap since -54 < 14
[12, -54, 14, 64, 90, 24] → [12, -54, 14, 64, 90, 24] — it will not swap since 14 < 64
[12, -54, 14, 64, 90, 24] → [12, -54, 14, 64, 90, 24] — it will not swap since 64 < 90
[12, -54, 14, 64, 90, 24] → [12, -54, 14, 64, 24, 90] — it will swap since 24 < 90
Second pass
[12, -54, 14, 64, 24, 90] → [-54, 12, 14, 64, 24, 90] — it will swap since -54 < 12
[-54, 12, 14, 64, 24, 90] → [-54, 12, 14, 64, 24, 90] — it will not swap since 12 < 14
[-54, 12, 14, 64, 24, 90] → [-54, 12, 14, 64, 24, 90] — it will not swap since 14 < 64
[-54, 12, 14, 64, 24, 90] → [-54, 12, 14, 24, 64, 90] — it will swap since 24 < 64
[-54, 12, 14, 24, 64, 90] → [-54, 12, 14, 24, 64, 90] — it will not swap since 64 < 90
Since the list is sorted after the second pass: [−54, 12, 14, 24, 64, 90], there is no need to proceed to the third and fourth pass.