python实现常用排序算法

2017-08-03  本文已影响0人  这个手刹丶不太灵

*排序算法

ordersummary

冒泡排序

原理:比较相邻的元素。如果第一个比第二个大,就交换他们两个。

def buttle_sort(l1):
    for i in range(len(l1)-1):
        flag = True
        for j in range(len(l1)-1-i):
            if l1[j] > l1[j+1]:
                l1[j],l1[j+1] = l1[j+1],l1[j]
                flag = False
        if flag:
            #某次内层循环没有交换,直接返回list
            return l1
    return l1

选择排序

原理:将后面的元素最小元素一个个取出然后按顺序放置

def selection_sort(l1):
    for i in range(len(l1)):
        min = i                      #最小元素下标
        for j in range(i+1,len(l1)):
            if l1[j] < l1[min]:
                min = j              #最小值下标
        l1[i],l1[min] = l1[min],l1[i]
    return l1

插入排序

原理:插入排序的工作原理是,对于每个未排序数据,在已排序序列中从后向前扫描,找到相应位置并插入。

def insert_sort(l1):
    n = len(l1)
    for i in range(1,n):
        if l1[i] < l1[i-1]:
            temp = l1[i]
            index = i           #待插入下标为index的元素
            for j in range(i-1,-1,-1):    #从i-1循环到0(包括0)
                if l1[j] > temp:
                    l1[j+1]     = l1[j]
                    index = j   #记录待插入下标
                else:
                    break
            l1[index] = temp
            print('L1~~~~~~~~%s ' % l1)
    return l1

希尔排序

原理:将数组列在一个表中并对列分别进行插入排序,重复这过程,不过每次用更长的列(步长更长了,列数更少了)来进行。

最后整个表就只有一列了。将数组转换至表是为了更好地理解这算法,算法本身还是使用数组进行排序。

def shell_sort(ary):
    n = len(ary)
    #初始步长 , 用round四舍五入取整
    gap = round(n/3) 
    while gap > 0 :
        print('gap %s' % gap)
        for i in range(gap,n): #每一列进行插入排序 , 从gap 到 n-1
            temp = ary[i]
            j = i
            while ( j >= gap and ary[j-gap] > temp ): #插入排序
                ary[j] = ary[j-gap]
                j = j - gap
            ary[j] = temp
        print(ary)
        gap = round(gap/3)  #重新设置步长
    return ary
### 13 14 94 33 82
### 25 59 94 65 23
### 45 27 73 25 39
### 10

l1= [ 13, 14, 94,33 ,82, 25, 59,94, 65, 23, 45, 27, 73, 25, 39, 10 ]
print(shell_sort(l1))

快速排序

原理:

上一篇 下一篇

猜你喜欢

热点阅读