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

Python Merge Sort

Python Merge Sort

Document Object Reference Manual Python3 Examples

Merge sort is an efficient sorting algorithm built upon the merge operation. It is a very typical application of the divide and conquer approach.

Divide and conquer:

Example

def

merge

(

arr

,

l

,

m

,

r

)

:

n1

=

m

l

1

n2

=

r

m

Create a temporary array

L

=

[

0

]

(

n1

)

R

=

[

0

]

(

n2

)

Copy data to temporary arrays L[] and R[]

for

i

in

range

(

0

,

n1

)

:

L

[

i

]

=

arr

[

l

i

]

for

j

in

range

(

0

,

n2

)

:

R

[

j

]

=

arr

[

m

1

j

]

Merge the temporary arrays into arr[l..r]

i

=

0

Initialize the index of the first subarray

j

=

0

Initialize the index of the second subarray

k

=

l

Initialize the index for merging the subarray

while

i

<

n1

and

j

<

n2

:

if

L

[

i

]

<=

R

[

j

]

:

arr

[

k

]

=

L

[

i

]

i

+=

1

else

:

arr

[

k

]

=

R

[

j

]

j

+=

1

k

+=

1

Copy the remaining elements of L[]

while

i

<

n1

:

arr

[

k

]

=

L

[

i

]

i

+=

1

k

+=

1

Copy the remaining elements of R[]

while

j

<

n2

:

arr

[

k

]

=

R

[

j

]

j

+=

1

k

+=

1

def

mergeSort

(

arr

,

l

,

r

)

:

if

l

<

r

:

m

=

int

(

(

l

(

r

1

)

)

/

2

)

mergeSort

(

arr

,

l

,

m

)

mergeSort

(

arr

,

m

1

,

r

)

merge

(

arr

,

l

,

m

,

r

)

arr

=

[

12

,

11

,

13

,

5

,

6

,

7

]

n

=

len

(

arr

)

print

(

"

The given array

"

)

for

i

in

range

(

n

)

:

print

(

"

%d

"

%

arr

[

i

]

)

,

mergeSort

(

arr

,

0

,

n

1

)

print

(

"

\n

\n

The sorted array

"

)

for

i

in

range

(

n

)

:

print

(

"

%d

"

%

arr

[

i

]

)

,

The output of the code above is:


给定的数组
12
11
13
5
6
7


排序后的数组
5
6
7
11
12
13

Document Object Reference Manual Python3 Examples