Python Shell Sort
Shell sort, also called the diminishing increment sort algorithm, is a more efficient improved version of insertion sort. However, Shell sort is not a stable sorting algorithm.
The basic idea of Shell sort is: first split the entire sequence of records to be sorted into several subsequences and perform direct insertion sort on each; once the records in the whole sequence are "basically ordered", perform one direct insertion sort over all the records.
Example
def
shellSort
(
arr
)
:
n
=
len
(
arr
)
gap
=
int
(
n
/
2
)
while
gap
0
:
for
i
in
range
(
gap
,
n
)
:
temp
=
arr
[
i
]
j
=
i
while
j
=
gap
and
arr
[
j
gap
]
temp
:
arr
[
j
]
=
arr
[
j
gap
]
j
-=
gap
arr
[
j
]
=
temp
gap
=
int
(
gap
/
2
)
arr
=
[
12
,
34
,
54
,
2
,
3
]
n
=
len
(
arr
)
(
"
Before sorting:
"
)
for
i
in
range
(
n
)
:
(
arr
[
i
]
)
,
shellSort
(
arr
)
(
"
\n
After sorting:
"
)
for
i
in
range
(
n
)
:
(
arr
[
i
]
)
,
The output of the code above is:
Before sorting:
12
34
54
2
3
After sorting:
2
3
12
34
54
Python3 Examples