CSC211 · 2081 · 5 marks
Sort the number {82, 73, 12, 39, 26, 88, 2, 9, 60, 41} using shell sort.
Sort the number {82, 73, 12, 39, 26, 88, 2, 9, 60, 41} using shell sort. [5]
Data Structures and AlgorithmsChapter 6: SortingComparison Sorting AlgorithmsNumerical: shell sort
Shell Sort: {82, 73, 12, 39, 26, 88, 2, 9, 60, 41}
Given
| Index | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
|---|---|---|---|---|---|---|---|---|---|---|
| Value | 82 | 73 | 12 | 39 | 26 | 88 | 2 | 9 | 60 | 41 |
- $n = 10$
- Increment sequence chosen: $k = 5, 2, 1$ (standard $n/2$ halving)
Solution
Pass 1: Increment $k = 5$
Sub-files (elements 5 positions apart):
| Sub-file | Indices | Values | Sorted |
|---|---|---|---|
| 1 | 0, 5 | {82, 88} | {82, 88} |
| 2 | 1, 6 | {73, 2} | {2, 73} |
| 3 | 2, 7 | {12, 9} | {9, 12} |
| 4 | 3, 8 | {39, 60} | {39, 60} |
| 5 | 4, 9 | {26, 41} | {26, 41} |
Array after Pass 1:
| Index | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
|---|---|---|---|---|---|---|---|---|---|---|
| Value | 82 | 2 | 9 | 39 | 26 | 88 | 73 | 12 | 60 | 41 |
Pass 2: Increment $k = 2$
Sub-files (elements 2 positions apart):
- Even indices ${0,2,4,6,8}$: {82, 9, 26, 73, 60} $\rightarrow$ {9, 26, 60, 73, 82}
- Odd indices ${1,3,5,7,9}$: {2, 39, 88, 12, 41} $\rightarrow$ {2, 12, 39, 41, 88}
Interleave back:
| Index | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
|---|---|---|---|---|---|---|---|---|---|---|
| Value | 9 | 2 | 26 | 12 | 60 | 39 | 73 | 41 | 82 | 88 |
Pass 3: Increment $k = 1$ (standard insertion sort)
Start: {9, 2, 26, 12, 60, 39, 73, 41, 82, 88}
- Insert 2: {2, 9, 26, 12, 60, 39, 73, 41, 82, 88}
- Insert 26: no change
- Insert 12: {2, 9, 12, 26, 60, 39, 73, 41, 82, 88}
- Insert 60: no change
- Insert 39: {2, 9, 12, 26, 39, 60, 73, 41, 82, 88}
- Insert 73: no change
- Insert 41: {2, 9, 12, 26, 39, 41, 60, 73, 82, 88}
- Insert 82: no change
- Insert 88: no change
Final Sorted Array
| 2 | 9 | 12 | 26 | 39 | 41 | 60 | 73 | 82 | 88 |
|---|
Result: ${2, 9, 12, 26, 39, 41, 60, 73, 82, 88}$
Short on time? The 1, 5 and 10 mark versions of this answer, flashcards and practice sets come with a program pass.