全站文章索引 📚📚📚

展開全部 | 收合全部

全站文章索引 📚📚📚

展開全部 | 收合全部

【演算法筆記 #3】QuickSort 重點整理筆記,包含 Partition, Pivot 常見錯誤討論 #重要題型

前言

QuickSort 算是面試中或是演算法中經典的問題,非常重要,
而且最容易搞錯「他的範圍」,因此這邊來將自己的常見錯誤做一個總整理。

先一個正式版本

基本上,要講出 QuickSort 的核心精神,人人幾乎都不太會犯錯,
但程式非常容易寫錯,特別是在區間的控制過程。

QuickSort 的核心精神

QuickSort 的核心精神就是選定一個 pivot (可以頭可以尾),
將剩下的數字透過 pivot 分成 「 < pivot 」 與 「 > pivot 」 兩組。

最容易出錯的地方 – 決定邊界

在撰寫程式的時候,如果沒有仔細思考,或甚至已經仔細思考了都還經常會寫錯。

注意:這邊示範的並「不是」主流的教科書寫法,而是用釐清觀念候「用自己的方式」寫的。

我們的目的如上圖,就是希望在循環結束時,能夠

  • 讓 left 左邊的一切都是 smaller (than pivot)
  • 讓 right 右邊的一切都是 bigger (than pivot)

因此 (以下為說明用的程式碼,並不完整)

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 <= right

首先是 left <= right,如果寫 left < right 達不到交錯的效果,有可能出迴圈要多做處理

不是不能這樣寫,就是要多做一些處理,沒有什麼不能的寫法

a[left] < pivot, a[right] > pivot

注意這裡不處理等於,原因是處理等於也不一定好,
等於表示與 pivot 相等,用於處理重複的 array,
但如果硬要處理等於的情況,在 [1,1,1,1,1] 類似這樣的 case,
一定會用 worst case 的 O(n) 時間去解,而不是平均的 O(nlogN)。

可以先理解 QuickSort 的 worst case 是什麼情況及為什麼會發生,
這樣更能夠懂為什麼會舉到上面的例子。

此種類的完整的 QuickSort 程式碼

    def partition(self, nums, start, end):
        # recusion end
        if start >= end:
            return 

        # recursion define
        left, right = start+1, end
        pivot = nums[start]

        while(left <= right):
            while(left <= right and nums[left] < pivot):
                left += 1
            while(left <= right and nums[right] > pivot):
                right -= 1
            if left <= right:
                nums[left], nums[right] = nums[right], nums[left]
        else:
            nums[start], nums[right] = nums[right], nums[start]

        print(nums, left, right)

        # recursion split
        self.partition(nums, start, right-1)
        self.partition(nums, left, end)

抓 partition 與 pivot 的重點

我們設計的思想是

  • 一開始:
    pivot(start) < (left, start+1) < (right, end)

  • 結束時,交換前 (注意交錯):

(start) < start+1 < right < left < end

務必注意交錯的位置的「 right < left 」,這是最最重要的部分。

  • 結束時,交換後 (注意交錯):

start < right-1 < pivot(right) < left < end

而 start ~ right-1 都比 pivot 小
left < end 都比 pivot 大。

結束迴圈 recursion 「start >= end」

不論是

  • self.partition(nums, start, right-1)
  • self.partition(nums, left, end)

right 會越來越逼近 start,直到重疊 start >= end
而 left 也會越來越逼近 end (因為 left 與 right 是交錯,只會更逼近 end)

另外一種寫法

建議先嘗試閱讀以下程式碼,思考一下
(這我寫過的東西,我也想了很久為什麼)

while(left <= right)
    if a[left] < pivot:
        left += 1
    elif a[right] > pivot:
        right -= 1
    else:
        a[left], a[right] = a[right], a[left]
        # left += 1
        # right -= 1

建議想好後再看,這樣才會更印象深刻。

注意 left <= right

一樣要注意的 left <= right,因為一定要交錯。

「left += 1」、「right -= 1」可有可無

其中「left += 1」、「right -= 1」可有可無,
沒有當下處理也會在之後的迴圈被處理掉。

此種類的完整的 QuickSort 程式碼

def partition(self, nums, start, end):
        # recusion end
        if start >= end:
            return 

        # recursion define
        left, right = start+1, end
        pivot = nums[start]

        while(left <= right):
            if nums[left] < pivot:
                left += 1 
            elif nums[right] > pivot:
                right -= 1 
            else:
                nums[left], nums[right] = nums[right], nums[left]
        else:
            nums[start], nums[right] = nums[right], nums[start]

        # recursion split
        self.partition(nums, start, right-1)
        self.partition(nums, left, end)

抓 partition 與 pivot 的重點

我們設計的思想是

  • 一開始:
    pivot(start) < (left, start+1) < (right, end)

  • 結束時,交換前 (注意交錯):

(start) < start+1 < right < left < end

務必注意交錯的位置的「 right < left 」,這是最最重要的部分。

  • 結束時,交換後 (注意交錯):

start < right-1 < pivot(right) < left < end

而 start ~ right-1 都比 pivot 小
left < end 都比 pivot 大。

結束迴圈 recursion 「start >= end」

不論是

  • self.partition(nums, start, right-1)
  • self.partition(nums, left, end)

right 會越來越逼近 start,直到重疊 start >= end
而 left 也會越來越逼近 end (因為 left 與 right 是交錯,只會更逼近 end)

Reference

⭐ Leetcode 解題紀錄 ⭐題型資料結構Python SolutionC++ SolutionNote
⭐BFS 相關題型 ⭐
104Maximum Depth of Binary TreeBFS (分層)Python
94Binary Tree Inorder TraversalBFS (分層)TreePython 內含 處理 Tree 樹問題的重點
102Binary Tree Level Order TraversalBFS (分層)TreePython
103Binary Tree Zigzag Level Order TraversalBFS (分層)TreePython
107Binary Tree Level Order Traversal IIBFS (分層)TreePython
133Clone GraphBFS (分層)GraphPython Graph 的基本操作 #重要題型
127Word LadderBFS (分層), DFSGraphPython
[Lint] 127Topological SortingBFS (拓撲)Python
內有 indegree, outdegree 介紹 #重要題型
207Course ScheduleBFS (拓樸)GraphPython
210Course Schedule IIBFS (拓樸)GraphPython
[Lint] 892Alien DictionaryBFS (拓樸)GraphPython
[Lint] 431Connected Component in Undirected GraphBFS (連通塊)GraphPython 內含 BFS 模板 #重要題型
1091Shortest Path in Binary MatrixBFS (最短路徑)MatrixPython
⭐ Binary Serach 相關題型 ⭐
33Search in Rotated Sorted ArrayBinary SerachArrayPython #重要題型
34Find First and Last Position of Element in Sorted ArrayBinary SerachPython
50Pow(x, n) Binary SerachPython
153Find Minimum in Rotated Sorted Array Binary SerachArrayPython
162Find Peak ElementBinary SerachPython
278First Bad VersionBinary SerachPython
658Find K Closest ElementsBinary SerachPython
704Binary SearchBinary SerachPython
852Peak Index in a Mountain ArrayBinary SerachPython
[Lint] 14First Position of TargetBinary SerachPython
[Lint] 140Fast PowerBinary SerachPython
[Lint] 447Search in a Big Sorted ArrayBinary SerachArrayPython
[Lint] 458Last Position of TargetBinary SerachPython
191Number of 1 BitsBit ManipulationPython
⭐ Data Stream 相關題型 ⭐
[Lint] 642Moving Average from Data StreamData StreamQueuePython
⭐ Design 相關題型 ⭐
155Min StackDesignPython
[Lint] 659Encode and Decode StringsDesignPython
232Implement Queue using StacksDesignQueue, StackPython
⭐ DFS 相關題型 ⭐
98Validate Binary Search TreeDFSPython
2265Count Nodes Equal to Average of SubtreeDFSPython
292nd Weekly Contest
2261K Divisible Elements SubarraysDFSPython
內含 python substring 常見作法 / 291st LeetCode Weekly Contest
22Generate ParenthesesDFSPython
79Word SearchDFSMatrixPython
126Word Ladder IIDFSPython
212Word Search IIDFSTreePython
290Word PatternDFSPython
[Lint] 829Word Pattern IIDFSPython
31Next PermutationDFS (排列)Python
46PermutationsDFS (排列)Python
#重要題型
47Permutations IIDFS (排列)Python
#重要題型
51N-QueensDFS (排列)Python
52N-Queens IIDFS (排列)Python
[Lint] 862Next Closest TimeDFS (排列)Python
內有 set 判斷是否 subset 的用法
10Regular Expression MatchingDFS (組合)Python
77CombinationsDFS (組合)Python
#重要題型
39Combination SumDFS (組合)Python
40Combination Sum IIDFS (組合)Python
216Combination Sum IIIDFS (組合)Python
377Combination Sum IVDFS (組合)Python
44Wildcard MatchingDFS (組合)Python
78SubsetsDFS (組合)Python
#重要題型
90Subsets IIDFS (組合)Python
#重要題型
131Palindrome PartitioningDFS (組合)Python
139Word BreakDFS (組合)Python
140Word Break IIDFS (組合)Python
[Lint] 90k Sum IIDFS (組合)Python
[Lint] 680Split StringDFS (組合)Python
173Binary Search Tree IteratorDFS (BST)BSTPython
#重要題型
230Kth Smallest Element in a BSTDFS (BST)BSTPython
[Lint] 448Inorder Successor in BSTDFS (BST)BSTPython
[Lint] 900Closest Binary Search Tree ValueDFS (BST)BSTPython
[Lint] 901Closest Binary Search Tree Value IIDFS (BST)BSTPython
#綜合難題
208Implement Trie (Prefix Tree)DFS (Graph)TreePython
17Letter Combinations of a Phone NumberDFS (Graph)GraphPython
332Reconstruct ItineraryDFS (Graph)GraphPython
#重要題型
110Balanced Binary TreeDFS (Tree)TreePython
226Invert Binary TreeDFS (Tree)TreePython
572Subtree of Another TreeDFS (Tree)TreePython
105Construct Binary Tree from Preorder and Inorder TraversalDFS (Tree)TreePython
112Path SumDFS (Tree)Python
113Path Sum IIDFS (Tree)TreePython
235Lowest Common Ancestor of a Binary Search TreeDFS (Tree)TreePython
236Lowest Common Ancestor of a Binary TreeDFS (Tree)TreePython
#重要題型
257Binary Tree PathsDFS (Tree)TreePython
[Lint] 474Lowest Common Ancestor IIDFS (Tree)TreePython
[Lint] 578Lowest Common Ancestor IIIDFS (Tree)TreePython
[Lint] 596Minimum SubtreeDFS (Tree)TreePython
543Diameter of Binary TreeDFS (Tree)Python
144Binary Tree Preorder TraversalDFS (Tree)TreePython
內含 處理 Tree 樹問題的重點
145Binary Tree Postorder TraversalDFS (Tree)TreePython
114Flatten Binary Tree to Linked ListDFS (Tree)TreePython
⭐ Dynamic Programming 相關題型 ⭐
338Counting BitsDPPython
309Best Time to Buy and Sell Stock with CooldownDPPython
2266Count Number of TextsDPPython
292nd Weekly Contest
2262Total Appeal of A StringDPPython
291st Weekly Contest
91Decode Ways DPPython C++
70Climbing Stairs DPPython C++
221Maximal SquareDPPython
53Maximum SubarrayDP (一維)ArrayPython C++ 內含 C++ vector max 用法整理
91Decode WaysDP (一維)Python
55Jump GameDP (一維)Python
#重要題型
45Jump Game IIDP (一維)Python
#重要題型
198House RobberDP (一維)Python
213House Robber IIDP (一維)Python
509Fibonacci NumberDP (一維)Python
122Best Time to Buy and Sell Stock IIDP (一維)Python
300Longest Increasing SubsequenceDP (一維接龍, LIS)Python
#重要題型
62Unique PathsDP (二維)Python C++
63Unique Paths IIDP (二維)Python C++
152Maximum Product SubarrayDP (二維)Python
#重要題型
118Pascal’s TriangleDP (二維)Python
內含 python sum of two list (list add 相加方法整理)
322Coin ChangeDP (背包問題)Python
內含 DP 背包問題模板 #重要題型
518Coin Change 2DP (背包問題)Python
#重要題型
[Lint] 92BackpackDP (背包問題)Python
[Lint] 125Backpack IIDP (背包問題)Python
[Lint] 440Backpack IIIDP (背包問題)Python
[Lint] 562Backpack IVDP (背包問題)Python
[Lint] 563Backpack VDP (背包問題)Python
[Lint] 798Backpack VIIDP (背包問題)Python
[Lint] 799Backpack VIIIDP (背包問題)Python
[Lint] 800Backpack IXDP (背包問題)Python
[Lint] 801Backpack XDP (背包問題)Python
1143Longest Common SubsequenceDP (LCS)Python
494Target SumDP (Memoization)Python
2267Check if There Is a Valid Parentheses String PathDP (Memoization)Python
內含:Memoization 記憶化搜索筆記 / 292nd Weekly Contest
⭐ Hash 相關題型 ⭐
13Roman to IntegerHashPython
73Set Matrix Zeroes HashPython C++ 內含 python while-else 用法說明
692Top K Frequent WordsHashPython
內含 python 自定義排序 key function 的使用方法
846Hand of StraightsHashPython
347Top K Frequent ElementsHashPython
205Isomorphic StringsHashPython
268Missing NumberHashPython
242Valid AnagramHashPython
763Partition LabelsHashIntervalPython
383Ransom NoteHashPython
387 First Unique Character in a String HashPython
2186Minimum Number of Steps to Make Two Strings Anagram IIHashPython
282nd Weekly Contest
[Lint] 793Intersection of ArraysHashPython
146LRU CacheHashPython
387First Unique Character in a StringHashPython
[Lint] 920Meeting RoomsHashIntervalPython
#重要題型
[Lint] 920Meeting RoomsHashIntervalPython
#重要題型
[Lint] 919Meeting Rooms IIHashIntervalPython
#重要題型
[Lint] 919Meeting Rooms IIHashIntervalPython
#重要題型
349 Intersection of Two ArraysHashPython
217Contains DuplicateHashArrayPython
C++ 內含 C++ set, unordered_set 用法整理
137Single Number IIHashPython
350Intersection of Two Arrays IIHashPython
2248Intersection of Multiple ArraysHashPython
290th Weekly Contest
49Group AnagramsHash (Anagrams)Python
217Contains DuplicateHash (Duplicate)Python
128Longest Consecutive SequenceHash (LCS)Python
136Single NumberHash, Bit ManipulationPython
⭐ Heap 相關題型 ⭐
264Ugly Number IIHeapPython
⭐ Stack 相關題型 ⭐
739Daily TemperaturesStackPython
496Next Greater Element IStackPython
503Next Greater Element IIStackPython
20Valid ParenthesesStack (Parentheses)Python
內含用 python List 組出 Stack, Queue 的方法整理
⭐ Two pointers 相關題型 ⭐
11Container With Most WaterTwo pointersPython
42Trapping Rain WaterTwo pointersPython
74Search a 2D Matrix Two pointersMatrixPython
141Linked List CycleTwo pointersLinked ListPython
142Linked List Cycle IITwo pointersLinked ListPython
內含 python while-else 用法介紹
283Move ZeroesTwo pointersPython
876Middle of the Linked ListTwo pointersPython
2260Minimum Consecutive Cards to Pick UpTwo pointers (快慢)Python
291st Weekly Contest
21Merge Two Sorted ListsTwo pointers (Merge)Linked ListPython
內含 python Linked List 基本操作 (for 新手教學)
88Merge Sorted Array Two pointers (Merge)Python C++ 內含 python while-else 用法說明
1Two SumTwo pointers (NSum)ArrayPython C++ 內有 Python list comprehesion / dict comprehesion 整理 / C++ map find 方法補充 (dict find)
153Sum Two pointers (NSum)ArrayPython
163Sum ClosestTwo pointers (NSum)Python
167Two Sum II – Input Array Is SortedTwo pointers (NSum)Python
[Lint] 382Triangle CountTwo pointers (NSum)Python
[Lint] 533Two Sum – Closest to TargetTwo pointers (NSum)Python
[Lint] 587Two Sum – Unique PairsTwo pointers (NSum)Python
5Longest Palindromic Substring Two pointers (Palindrome)Python C++ 內含 C++ string.substr() 用法筆記
9Palindrome NumberTwo pointers (Palindrome)Python
125Valid PalindromeTwo pointers (Palindrome)StringPython內含 python isalpha(), isalnum() 的整理
680Valid Palindrome IITwo pointers (Palindrome)Python
409Longest Palindrome
Two pointers (Palindrome)Python
647Palindromic SubstringsTwo pointers (Palindrome)Python
234Palindrome Linked ListTwo pointers (Palindrome)Linked ListPython
內含 reverse LinkedList 方法
75Sort ColorsTwo pointers (partition)Python
#重要題型
[Lint] 5Kth Largest ElementTwo pointers (partition)Python
#重要題型
[Lint] 31Partition ArrayTwo pointers (partition)Python
#重要題型
[Lint] 143Sort Colors IITwo pointers (partition)Python
#重要題型
[Lint] 461Kth Smallest Numbers in Unsorted ArrayTwo pointers (partition)Python
#重要題型
3Longest Substring Without Repeating CharactersTwo pointers (Sliding Window)Python
76 Minimum Window SubstringTwo pointers (Sliding Window)Python
239Sliding Window MaximumTwo pointers (Sliding Window)Python
⭐ 其他題型 / 待分類 ⭐
2Add Two NumbersLinked ListPython
7Reverse IntegerPython
19Remove Nth Node From End of ListLinked ListPython
36Valid SudokuPython
48Rotate ImageMatrixPython
621Task SchedulerPython
202Happy NumberPython
238Product of Array Except SelfPython
222Count Complete Tree NodesTreePython
674Longest Continuous Increasing SubsequencePython
435Non-overlapping IntervalsIntervalPython
88Merge Sorted ArrayPython
內含 python while-else 用法說明
2264Largest 3-Same-Digit Number in StringPython
292nd Weekly Contest
56Merge IntervalsIntervalPython
內含:python sorted key 搭配 lambda 的用法範例
57Insert IntervalIntervalPython
61Rotate ListLinked ListPython
2259Remove Digit From Number to Maximize ResultPython
291st Weekly Contest
53Maximum SubarrayPython
54Spiral MatrixPython
228Summary RangesPython
263Ugly NumberPython
203Remove Linked List ElementsLinked ListPython
內含 Linked List remove 操作 part 2 (for 新手教學)
206Reverse Linked ListLinked ListPython
內含 Linked List reverse 反轉操作 part 3 (for 新手教學)
189Rotate ArrayArrayPython
2185Counting Words With a Given PrefixStringPython
282nd Weekly Contest
134Gas StationPython
121Best Time to Buy and Sell StockPython
83Remove Duplicates from Sorted ListLinked ListPython
566Reshape the MatrixMatrixPython
內含 python array 初始化, index 操作與控制範例
2243Calculate Digit Sum of a StringPython
289th Weekly Contest
2244Minimum Rounds to Complete All TasksPython
289th Weekly Contest
2249Count Lattice Points Inside a CirclePython
290th Weekly Contest
⭐【喜歡我的文章嗎? 歡迎幫我按讚~ 讓基金會請創作者喝一杯咖啡!
如果喜歡我的文章,請幫我在下方【按五下Like】 (Google, Facebook 免註冊),會由 「LikeCoin」 贊助作者鼓勵繼續創作,讀者們「只需幫忙按讚,完全不用出錢」哦!

likecoin-steps
Howard Weng
Howard Weng

我是 Howard Weng,很多人叫我嗡嗡。這個網站放了我的各種筆記。希望這些筆記也能順便幫助到有需要的人們!如果文章有幫助到你的話,歡迎幫我點讚哦!
另外,因為定位是「個人的隨手筆記」,有些文章內容「⚠️可能我理解有誤⚠️」或「🥱只寫到一半😴」,如果有發現這樣的情況,歡迎在該文章的最下面留言提醒我!我會儘快修正或補上!感謝大家的建議與幫忙,讓網站能變得更好🙏

文章: 795

2 則留言

    • 我覺得要看情況,
      1. 如果是”準備面試”我建議 iterative 或 recursion(遞迴) 兩種方法都要會
      2. 實務上應用的話,現在其實各大語言都也有內建的 sort function 能直接用,也不用自己寫XD
      3. 至於如果只是單純想實現這個演算法,recursion 寫起來簡潔,但容易在終止條件出錯,思考程式運作上也比較難想(遞迴天生的特性)
      iterative 比較不容易寫錯,也比較容易腦中直接思考出程式在幹嘛。

      (這部分只是我個人的經驗談,拿去問別人這問題一定也會有不同的答案XD)

★留個言吧!內容有誤或想要補充也歡迎與我討論!