常用排序算法

常見排序演示http://www.cs.usfca.edu/~galles/visualization/ComparisonSort.html

1.Bubble sort
solution:兩兩交換

class Solution:
    def bubble_sort(self, A):
        len_a = len(A)
        if len_a < 2:
            return
        for i in range(len_a):
            for j in range(len_a - 1 -i):
                if A[j] > A[j + 1]:
                    A[j], A[j + 1] = A[j + 1], A[j]

2.Quick Sort
solution:從上到下分治

class Solution:
    def quick_sort(self, A, start, end):
        if stat >= end:
            return 

        left, right = start, end

        #pivot is value not index
        pivot = A[(start + end) / 2]

        #every time you compare left & right, it should be left <= right
        while left <= right:
            while left <= right and A[left] < pivot:
                left += 1
            
            while left <= right and A[right] > pivot:
                right -= 1
            
            if left <= right:
                A[left], A[right] = A[right], A[left]

                left += 1
                right -= 1
        self.quick_sort(self, A, start, right)
        self.quick_sort(self, A, left, end)

3.Merge Sort
solution:從下到上分治

class Solution:
    # @param {int[]} A an integer array
    # @return nothing
    def merge_sort(self, start, end, A, temp):
        if start >= end:
            return
        
        mid = (start + end) / 2
        self.merge_sort(start, mid , A, temp)
        self.merge_sort(mid + 1, end, A, temp)
        self.merge(start, mid, end, A, temp)
        
    def merge(self, start, mid, end, A, temp):
        left, right = start, mid + 1
        index = start
        while left <= mid and right <= end:
            if A[left] < A[right]:
                temp[index] = A[left]
                left += 1
            else:
                temp[index] = A[right];
                right += 1
                
            index += 1
            
        while left <= mid:
            temp[index] = A[left]
            left += 1
            index += 1
            
        while right <= end:
            temp[index] = A[right]
            right += 1
            index += 1
            
        for index in range(start, end + 1):
            A[index] = temp[index]

4.[Merge Two Sorted Arrays]https://leetcode.com/problems/merge-sorted-array/description/
solution:數(shù)組的首位進(jìn)行比較,小的放進(jìn)去馋贤,依次進(jìn)去
一般遇到Merge這種合并的方式,都會(huì)涉及到3的歸并排序,兩兩比較然后放到數(shù)組或者新開的buffer里面躲惰。比完之后周霉,總有一個(gè)數(shù)組或者一個(gè)區(qū)間沒有出完翰苫,那就繼續(xù)
Notice:在快排和歸并排序里面,都有l(wèi)eft, right温技,其中對(duì)于快排,left = start, right = end,從兩邊開始往里走扭粱。對(duì)于歸并排序而言舵鳞,left = start, right = mid + 1。分別從區(qū)間的頭部開始琢蛤。而且對(duì)于不同數(shù)組而言蜓堕,使用"<" ,對(duì)于不同區(qū)間而言博其,使用"<="

class Solution(object):
    def merge(self, nums1, m, nums2, n):
        """
        :type nums1: List[int]
        :type m: int
        :type nums2: List[int]
        :type n: int
        :rtype: void Do not return anything, modify nums1 in-place instead.
        """
        result = []
        left, right = 0, 0
        
        while left < m and right < n:
            if nums1[left] < nums2[right]:
                result.append(nums1[left])
                left += 1
            else:
                result.append(nums2[right])
                right += 1
            
        while left < m:
            result.append(nums1[left])
            left += 1
        while right < n:
            result.append(nums2[right])
            right += 1
            
        for i in range(m + n):
            nums1[i] = result[i]

5.[Sort Integers II] http://www.lintcode.com/en/problem/sort-integers-ii/#
solution:這道題非常好的聯(lián)系歸并排序和快排的題目套才,下面分別用這兩種方法解題

@mergeSort
class Solution:
    """
    @param A: an integer array
    @return: nothing
    """
    def sortIntegers2(self, A):
        # write your code here
        len_a = len(A)
        temp = [0 for _ in range(len_a)]
        self.mergeSort(A, 0, len_a - 1, temp)
        
    def mergeSort(self, A, start, end, temp):
        if start >= end:
            return
        
        mid = (start + end) / 2
        self.mergeSort(A, start, mid, temp)
        self.mergeSort(A, mid + 1, end, temp)
        self.merge(A, start, end ,temp)
        
    def merge(self, A, start, end, temp):
        mid = (start + end) / 2
        left, right = start, mid + 1
        index = start
        
        while left <= mid and right <= end:
            if A[left] < A[right]:
                temp[index] = A[left]
                left += 1
                index += 1
            else:
                temp[index] = A[right]
                right += 1
                index += 1
                
        while left <= mid:
            temp[index] = A[left]
            left += 1
            index += 1
            
        while right <= end:
            temp[index] = A[right]
            right += 1
            index += 1
            
        for index in range(start, end + 1):
            A[index] = temp[index]
@quickSort
class Solution:
    """
    @param A: an integer array
    @return: nothing
    """
    def sortIntegers2(self, A):
        # write your code here
        self.quickSort(A, 0, len(A) - 1)
        
    def quickSort(self, A, start, end):
        if start >= end:
            return
        
        left, right = start, end
        pivot = A[(start + end) / 2]
        #這里pivot是指
        #區(qū)間永遠(yuǎn)都是<=
        
        while left <= right:
            while left <= right and A[left] < pivot:
                left += 1
            
            while left <= right and A[right] > pivot:
                right -= 1
                
            if left <= right:
                A[left], A[right] = A[right], A[left]
                left += 1
                right -= 1
                
        self.quickSort(A, start, right)
        self.quickSort(A, left, end)      
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市慕淡,隨后出現(xiàn)的幾起案子背伴,更是在濱河造成了極大的恐慌,老刑警劉巖峰髓,帶你破解...
    沈念sama閱讀 222,104評(píng)論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件傻寂,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡携兵,警方通過查閱死者的電腦和手機(jī)疾掰,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,816評(píng)論 3 399
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來徐紧,“玉大人静檬,你說我怎么就攤上這事勒葱。” “怎么了巴柿?”我有些...
    開封第一講書人閱讀 168,697評(píng)論 0 360
  • 文/不壞的土叔 我叫張陵凛虽,是天一觀的道長。 經(jīng)常有香客問我广恢,道長凯旋,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 59,836評(píng)論 1 298
  • 正文 為了忘掉前任钉迷,我火速辦了婚禮至非,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘糠聪。我一直安慰自己荒椭,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 68,851評(píng)論 6 397
  • 文/花漫 我一把揭開白布舰蟆。 她就那樣靜靜地躺著趣惠,像睡著了一般。 火紅的嫁衣襯著肌膚如雪身害。 梳的紋絲不亂的頭發(fā)上味悄,一...
    開封第一講書人閱讀 52,441評(píng)論 1 310
  • 那天,我揣著相機(jī)與錄音塌鸯,去河邊找鬼侍瑟。 笑死,一個(gè)胖子當(dāng)著我的面吹牛丙猬,可吹牛的內(nèi)容都是我干的涨颜。 我是一名探鬼主播,決...
    沈念sama閱讀 40,992評(píng)論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼茧球,長吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼庭瑰!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起袜腥,我...
    開封第一講書人閱讀 39,899評(píng)論 0 276
  • 序言:老撾萬榮一對(duì)情侶失蹤见擦,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后羹令,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體鲤屡,經(jīng)...
    沈念sama閱讀 46,457評(píng)論 1 318
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,529評(píng)論 3 341
  • 正文 我和宋清朗相戀三年福侈,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了酒来。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,664評(píng)論 1 352
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡肪凛,死狀恐怖堰汉,靈堂內(nèi)的尸體忽然破棺而出辽社,到底是詐尸還是另有隱情,我是刑警寧澤翘鸭,帶...
    沈念sama閱讀 36,346評(píng)論 5 350
  • 正文 年R本政府宣布滴铅,位于F島的核電站,受9級(jí)特大地震影響就乓,放射性物質(zhì)發(fā)生泄漏汉匙。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 42,025評(píng)論 3 334
  • 文/蒙蒙 一生蚁、第九天 我趴在偏房一處隱蔽的房頂上張望噩翠。 院中可真熱鬧,春花似錦邦投、人聲如沸伤锚。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,511評(píng)論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽屯援。三九已至,卻和暖如春蠢涝,著一層夾襖步出監(jiān)牢的瞬間玄呛,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,611評(píng)論 1 272
  • 我被黑心中介騙來泰國打工和二, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人耳胎。 一個(gè)月前我還...
    沈念sama閱讀 49,081評(píng)論 3 377
  • 正文 我出身青樓惯吕,卻偏偏與公主長得像,于是被迫代替她去往敵國和親怕午。 傳聞我的和親對(duì)象是個(gè)殘疾皇子废登,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,675評(píng)論 2 359

推薦閱讀更多精彩內(nèi)容