KnowledgeBoat Logo
|

Computer Science

Write the steps to arrange the following elements using insertion sort:

12, 5, 14, 8, 3, 54, 25, 10, 27, 30

Python List Manipulation

2 Likes

Answer

list = [12, 5, 14, 8, 3, 54, 25, 10, 27, 30]

First pass

[12, 5, 14, 8, 3, 54, 25, 10, 27, 30] → [5, 12, 14, 8, 3, 54, 25, 10, 27, 30] — it will swap since 5 < 12

Second pass

[5, 12, 14, 8, 3, 54, 25, 10, 27, 30] → [5, 12, 14, 8, 3, 54, 25, 10, 27, 30] — it will not swap since 12 < 14

Third pass

[5, 12, 14, 8, 3, 54, 25, 10, 27, 30] → [5, 12, 8, 14, 3, 54, 25, 10, 27, 30] — it will swap since 8 < 14
[5, 12, 8, 14, 3, 54, 25, 10, 27, 30] → [5, 8, 12, 14, 3, 54, 25, 10, 27, 30] — it will swap since 8 < 12

Fourth pass

[5, 8, 12, 14, 3, 54, 25, 10, 27, 30] → [5, 8, 12, 3, 14, 54, 25, 10, 27, 30] — it will swap since 3 < 14
[5, 8, 12, 3, 14, 54, 25, 10, 27, 30] → [5, 8, 3, 12, 14, 54, 25, 10, 27, 30] — it will swap since 3 < 12
[5, 8, 3, 12, 14, 54, 25, 10, 27, 30] → [5, 3, 8, 12, 14, 54, 25, 10, 27, 30] — it will swap since 3 < 8
[5, 3, 8, 12, 14, 54, 25, 10, 27, 30] → [3, 5, 8, 12, 14, 54, 25, 10, 27, 30] — it will swap since 3 < 5

Fifth pass

[3, 5, 8, 12, 14, 54, 25, 10, 27, 30] → [3, 5, 8, 12, 14, 54, 25, 10, 27, 30] — it will not swap since 14 < 54

Sixth pass

[3, 5, 8, 12, 14, 54, 25, 10, 27, 30] → [3, 5, 8, 12, 14, 25, 54, 10, 27, 30] — it will swap since 25 < 54

Seventh pass

[3, 5, 8, 12, 14, 25, 54, 10, 27, 30] → [3, 5, 8, 12, 14, 25, 10, 54, 27, 30] — it will swap since 10 < 54
[3, 5, 8, 12, 14, 25, 10, 54, 27, 30] → [3, 5, 8, 12, 14, 10, 25, 54, 27, 30] — it will swap since 10 < 25
[3, 5, 8, 12, 14, 10, 25, 54, 27, 30] → [3, 5, 8, 12, 10, 14, 25, 54, 27, 30] — it will swap since 10 < 14
[3, 5, 8, 12, 10, 14, 25, 54, 27, 30] → [3, 5, 8, 10, 12, 14, 25, 54, 27, 30] — it will swap since 10 < 12

Eighth pass

[3, 5, 8, 10, 12, 14, 25, 54, 27, 30] → [3, 5, 8, 10, 12, 14, 25, 27, 54, 30] — it will swap since 27 < 54

Ninth pass

[3, 5, 8, 10, 12, 14, 25, 27, 54, 30] → [3, 5, 8, 10, 12, 14, 25, 27, 30, 54] — it will swap since 30 < 54

After the Ninth pass of insertion sort, the list is: [3, 5, 8, 10, 12, 14, 25, 27, 30, 54]

Answered By

1 Like


Related Questions