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

Python Insertion Sort

Python Insertion Sort

Document Object Reference Manual Python3 Examples

Insertion sort is a simple and intuitive sorting algorithm. Its working principle is to build a sorted sequence, and for unsorted data, scan backward from the end of the sorted sequence to find the appropriate position and insert it.

Example

def

insertionSort

(

arr

)

:

for

i

in

range

(

1

,

len

(

arr

)

)

:

key

=

arr

[

i

]

j

=

i

1

while

j

=

0

and

key

<

arr

[

j

]

:

arr

[

j

1

]

=

arr

[

j

]

j

-=

1

arr

[

j

1

]

=

key

arr

=

[

12

,

11

,

13

,

5

,

6

]

insertionSort

(

arr

)

print

(

"

Sorted array:

"

)

for

i

in

range

(

len

(

arr

)

)

:

print

(

"

%d

"

%

arr

[

i

]

)

The output of the code above is:


Sorted array:
5
6
11
12
13

Document Object Reference Manual Python3 Examples