数据结构与算法(15)——冒泡法和选择法排序

  • 冒泡法排序

算法思路:在对对无序表进行多趟比较。

  • 代码思路
def bubbleSort(alist):
    '''
    始终将最大的放到最后一位
    :param alist:
    :return:
    '''
    for passnum in range(len(alist)-1,0,-1):
        for i in range(passnum):
            if alist[i] > alist[i +1]:
                alist[i], alist[i+1] = alist[i+1], alist[i]
alist = [54, 26, 93, 17, 77, 31, 44, 55, 20]
bubbleSort(alist)
print(alist)
def bubbleSort(alist):
    '''
    :param alist:
    :return:
    '''
    for i in range(len(alist)):
        for j in range(len(alist)-i-1):
            if alist[j] > alist[j+1]: #从小到大排序
                alist[j], alist[j+1] = alist[j+1], alist[j]
alist = [54, 26, 93, 17, 77, 31, 44, 55, 20]
bubbleSort(alist)
print(alist)

 

#减少遍历次数
def bubbleSort(alist):
    '''
    始终将最大的放到最后一位
    :param alist:
    :return:
    '''
    passnum = len(alist) -1
    exchange = True
    while passnum >0 and exchange:
        exchange = False #如果一趟下来都没有交换过大小,则说明list已经排好序
        for i in range(passnum):
            if alist[i] > alist[i + 1]:
                alist[i], alist[i + 1] = alist[i + 1], alist[i]
                exchange = True
        passnum = passnum -1
alist = [54, 26, 93, 17, 77, 31, 44, 55, 20]
bubbleSort(alist)
print(alist)
  • 选择法排序

对冒泡排序进行了改进,保留多趟对比的思路,但是每一次只是记录了最大项的索引,因此每趟制作一次交换。

比对复杂度还是o(n^2)交换次数的复杂度是O(n)

#solution3
#选择排序
def selectionSort(alist):
    for fillslot in range(len(alist)-1,0,-1):
        positionOfMax = 0
        for location in range(1, fillslot+1):
            if alist[location] > alist[positionOfMax]:
                positionOfMax = location
        temp = alist[fillslot]
        alist[fillslot] = alist[positionOfMax] #将最大项的位置和最后一项进行一次交换
        alist[positionOfMax] = temp
alist = [54, 26, 93, 17, 77, 31, 44, 55, 20]
selectionSort(alist)
print(alist)
posted @ 2020-07-18 21:58  Yelush  阅读(291)  评论(0)    收藏  举报