pythonアルゴリズムノート--ソート(バブル、選択、挿入)


1.pythonバブルソートを実現する:
原理:合計end-1回の泡が必要で、最大数は「泡」によって最後の位置に1回の泡が必要で、合計end-1回の交換が必要です.
class maopao:
    def __init__(self):
        self.a = [3,6,8,4,2,1,1]
    def oo_order(self):
        end = len(self.a)
        for j in range(0,end-1):#      end-1 ,      “  ”       
            for i in range(0,end-1):#           end-1 
                if self.a[i] > self.a[i+1]:
                    temp = self.a[i]
                    self.a[i] = self.a[i+1]
                    self.a[i+1] = temp
            end -= 1
        print(self.a)

if __name__ == '__main__':
    arg = maopao()
    arg.oo_order()

2.ソートの選択
class xuanzeOrder:
    def __init__(self):
        self.a = [2,4,6,8,5,3,4,6,9]


    def xzOrder(self):
        for i in range(0,len(self.a)):#  0~len-1,         
            minIndex = i
            for j in range(i+1,len(self.a)):#  i+1~len-1,        
                minIndex = j if(self.a[j] < self.a[minIndex]) else minIndex
            self.swap(i,minIndex)
        print(self.a)
        #  
    def swap(self,i,minIndex):
        temp = self.a[i]
        self.a[i] = self.a[minIndex]
        self.a[minIndex] = temp

if __name__ == '__main__':
    arg = xuanzeOrder()
    arg.xzOrder()

ソートの挿入
class insertOrder:
    def __init__(self):
        self.a = [4,2,6,8,5,3,4,6,9]
    def inseOrder(self):
        for i in range(1,len(self.a)):#  0~len-1
            for j in range(i-1,-1,-1):#  i-1~0
                if self.a[j] > self.a[j+1]:
                   self.swap(j,j+1)
        print(self.a)

    def swap(self,m,n):
        temp = self.a[m]
        self.a[m] = self.a[n]
        self.a[n] = temp

if __name__ == '__main__':
    arg = insertOrder()
    arg.inseOrder()