Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Shell Sort

Python Shell Sort

Document Object Reference Manual Python3 Examples

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

)

print

(

"

Before sorting:

"

)

for

i

in

range

(

n

)

:

print

(

arr

[

i

]

)

,

shellSort

(

arr

)

print

(

"

\n

After sorting:

"

)

for

i

in

range

(

n

)

:

print

(

arr

[

i

]

)

,

The output of the code above is:


Before sorting:
12
34
54
2
3

After sorting:
2
3
12
34
54

Document Object Reference Manual Python3 Examples