Python Exercise Example 39
**Problem:** There is an already sorted array. Now enter a number and insert it into the array according to the original order.
**Program analysis:** First determine whether the number is greater than the last number, then consider the case of inserting it in the middle. After insertion, the numbers after this element are shifted back one position in turn.
Program source code:
Example (Python 2.0+)
#!/usr/bin/python
-- coding: UTF-8 --
if
name
==
'
main
'
:
Method 1: 0 as a placeholder for the number to be added
a
=
[
1
,
4
,
6
,
9
,
13
,
16
,
19
,
28
,
40
,
100
,
0
]
(
'
Original list:
'
)
for
i
in
range
(
len
(
a
)
)
:
(
a
[
i
]
)
number
=
int
(
input
(
"
\n
Insert a number:
\n
"
)
)
end
=
a
[
9
]
if
number
end
:
a
[
10
]
=
number
else
:
for
i
in
range
(
10
)
:
if
a
[
i
]
number
:
temp1
=
a
[
i
]
a
[
i
]
=
number
for
j
in
range
(
i
1
,
11
)
:
temp2
=
a
[
j
]
a
[
j
]
=
temp1
temp1
=
temp2
break
(
'
Sorted list:
'
)
for
i
in
range
(
11
)
:
(
a
[
i
]
)
The output of the above example is:
Original list:
1
4
6
9
13
16
19
28
40
100
0
Insert a number:
7
Sorted list:
1
4
6
7
9
13
16
19
28
40
100
Python 100 Examples