Using Python for merge sorting

Source: Internet
Author: User

Use Python for merge sorting, excerpt from http://blog.csdn.net/minxihou/article/details/51821052

“代码真的不是一气呵成的,而且也不是想当然写出来的。可能需要反复断点中断来查看是否有逻辑错误。在理解了问题的基础下我们需要先把大体的代码框架最好先写出来,
特别是主要的逻辑判断语句。但是不需要太care我循环体或者判断里面语句怎么实现,当你把这一步做到的时候能避免很多不必要的错误发生。”
1 ImportRandom2 3 defconfiationalgorithm (str):4     ifLen (str) <= 1:#Sub-sequence5         returnStr6Mid = (len (str)//2)7left = Confiationalgorithm (Str[:mid])#Recursive slicing operations8right =Confiationalgorithm (str[mid:])9result = []Ten     #i,j = 0,0 One  A      whileLen (left) > 0 andLen (right) >0: -         if(Left[0] <=right[0]): -             #result.append (left[0]) the result.append (left.pop (0)) -             #i+= 1 -         Else: -             #result.append (right[0]) + result.append (right.pop (0)) -             #j+= 1 +  A     if(Len (left) >0): at Result.extend (Confiationalgorithm (left)) -     Else: - Result.extend (Confiationalgorithm (right)) -     returnresult -  - if __name__=='__main__': inA = [20,30,64,16,8,0,99,24,75,100,69] -     Print(Confiationalgorithm (a)) tob = [Random.randint (1,1000) forIinchRange (10)] +     Print(Confiationalgorithm (b))

Another way of thinking

1 defmerge (left, right):2I, j =0, 03result = []4      whileI < Len (left) andJ <Len (right):5         ifLeft[i] <=Right[j]:6 result.append (Left[i])7i + = 18         Else:9 result.append (Right[j])TenJ + = 1 OneResult + =Left[i:] AResult + =Right[j:] -     returnresult -  the defmerge_sort (lists): -     #Merge Sort -     ifLen (lists) <= 1: -         returnlists +num = Len (lists)/2 -left =Merge_sort (Lists[:num]) +right =Merge_sort (lists[num:]) A     returnMerge (left, right)

 

Using Python for merge sorting

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.