码迷,mamicode.com
首页 > 编程语言 > 详细

排序算法整理(python version)

时间:2018-01-19 11:50:04      阅读:160      评论:0      收藏:0      [点我收藏+]

标签:class   冒泡   pre   post   log   i+1   sel   append   style   

import random
import time

def bubble_sort(a):
    n=len(a)
    while n>1:
      for i in range(n-1):
        if a[i]>a[i+1]:
            temp=a[i]
            a[i]=a[i+1]
            a[i+1]=temp
      n+=-1
    return a

def insert_sort(a):
    n=len(a)
    for i in range(1,n):
      for j in range(i):
            if a[j]>a[i]:
              temp=a[i]
              del a[i]
              a.insert(j,temp)
              break
      print a

def select_sort(a):
    n=len(a)
    for i in range(n-1):
        minn= a[i]
        j=i
        for j in range(i,n):
            if a[j]<=minn:
                 minn=a[j]
                 k=j
        a[i],a[k]=minn,a[i]
        print a

def quick_sort(a):
    n=len(a)
    if n<2:
        return a
    i=0
    j=n-1
    pivot=a[0]
    while i<j:
        while i<j and a[j]>=pivot:
            j-=1
        a[i],a[j]=a[j],a[i]
        while i<j and a[i]<=pivot:
            i+=1
        a[i],a[j]=a[j],a[i]
    return quick_sort(a[:i])+[pivot]+quick_sort(a[i+1:])

def merge_sort(a):
    result=[]
    n=len(a)
    if n<2:
        return a
    mid=n/2
    b=merge_sort(a[:mid])
    c=merge_sort(a[mid:])
    i=0
    j=0
    while i<mid and j<mid:
        if b[i]>c[j]:
            result.append(c[j])
            j+=1
        else:
            result.append(b[i])
            i+=1
    result=result+b[i:]+c[j:]
    return result


if __name__==__main__:
    a=[]
    for i in range(20):
        a.append(random.randint(1,20))
    print quick_sort(a)

快排不稳定性体现在,当列表为[5,2,4,6,1,1]时,pivot为5,会把最后一个1与5交换,这样就改变了两个1之间的相对位置

当序列有序时,快排退化为冒泡排序

排序算法整理(python version)

标签:class   冒泡   pre   post   log   i+1   sel   append   style   

原文地址:https://www.cnblogs.com/luozx207/p/8315349.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!