Python realizes merge sort algorithm _python

Source: Internet
Author: User
Theory does not say much:
Copy Code code as follows:

#!/usr/bin/python
Import Sys

def merge (array, q, p, r):
Left_array = array[q:p+1]
Right_array = array[p+1:r+1]

Left_array_num = Len (left_array)
Right_array_num = Len (right_array)

I, J, k= [0, 0, Q]
While I < Left_array_num and J < right_array_num:
if (Left_array[i] < right_array[j]):
ARRAY[K] = Left_array[i]
I+=1
Else
ARRAY[K] = Right_array[j]
J+=1
K+=1

While I < left_array_num:
ARRAY[K] = Left_array[i];
K+=1
I+=1

While J < right_array_num:
ARRAY[K] = Right_array[j]
K+=1
J+=1

def merge_sort (Array, q, R):
If q < r:
p = (q + r)/2
Merge_sort (Array, q, p)
Merge_sort (Array, p + 1, R)
Merge (array, q, p, R)

if __name__ = = "__main__":
Array = [2, 45, 5, 7, 34, 456, 345, 89, 8, 1, 341, 4, 98, 67]
Merge_sort (array, 0, Len (array)-1)

For a in array:
Sys.stdout.write ("%d"% a)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.