Python版插入排序和歸并排序

jopen 11年前發布 | 17K 次閱讀 Python Python開發

  由于寫算法實驗,用C++寫的,最近學Python正好用Python實現熟練一下,發現簡潔很多,用著太方便了

下面貼代碼,這倆個排序比較簡單,不加注釋了。

 

#_*_coding:utf_8_
class Sort():
    def __int__(self):
        self.array = []
        self.size = 0

    def InitArray(self):
        n = raw_input()
        self.size = int(n)
        for i in range(self.size):
            data = raw_input()
            data = int(data)
            self.array.append(data)

    def PrintArray(self):
        for i in range(self.size):
            print self.array[i] ,
        print '\n'

class MyInsertSort(Sort):

    def __init__(self):
        self.size = 0 
        self.array = []

    #InitArray        
    def insertSort(self):
        for i in range(1, self.size):
            key = self.array[i]
            j = i - 1
            while j >= 0 and self.array[j] > key:
                self.array[j + 1] = self.array[j]
                j = j - 1        
            self.array[j + 1] = key


    #PrintArray 
    def ExcuteInsertSort(self):
        self.InitArray()
        self.insertSort()
        self.PrintArray()

#obj = MyInsertSort()
#obj.ExcuteInsertSort()


class MergeSort(Sort):
    def __init__(self):
        self.size = 0
        self.array = []
        self.B = []

    def MergeSort(self, low, high):
        if low < high:
            mid = low + (high - low)/2
            self.MergeSort(low, mid)
            self.MergeSort(mid+1, high)
            self.Merge(low, mid, high)

    def Merge(self, low, mid, high):
        i = low 
        j = mid + 1
        self.B = []
        while i <= mid and j <= high:
            if self.array[i] <= self.array[j]:
                self.B.append(self.array[i])
                i += 1
            else:
                self.B.append(self.array[j])
                j += 1

        while i <= mid:
           self.B.append(self.array[i])
           i += 1

        while j <= high:
            self.B.append(self.array[j]) #???bug
            j += 1
        index = 0
        for i in range(low, high+1):
            self.array[i] = self.B[index]
            index += 1

    def ExcuteMergeSort(self):
        self.InitArray()
        self.MergeSort(0, self.size-1)
        self.PrintArray()

obj = MergeSort()
obj.ExcuteMergeSort()
 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!