03 Sorting Algorithms
這篇筆記是我參考【演算法圖鑑】和網路資源所製作。如果內容有誤,還請不吝賜教!
Table of Content
Selection Sort - 選擇排序
Operation
- Find the minimum value in the sequence.
- Switch it with the leftmost item.
- Repeating 1 - 2 until the sequence is sorted.
Time Complexity
Implementation
Insertion Sort - 插入排序
Operations
- Start from the left item, and keep moving onto the right term. Let's say the index for this step is .
- Insert ( is the sequence) in the subsequence so that is still in ascending/decreasing order.
- Repeat 1 - 2 until the sequence is sorted.
Time Complexity
Implementation
Bubble Sort - 氣泡排序
Operations
(P.S. following shows how to sort the sequence in ascending order)
- Start from the left item, and keep moving onto the right term. Let's say the index for this step is .
- Compare and . If , then swap these two items. Otherwise do nothing.
- Repeat 1 - 2 until is the last item. Then = 0 again.
- Repeat 1 - 3 until is sorted.
Time Complexity
Implementation
Quick Sort - 快速排序
Operations
Quick sort requires a very important algorithm - D&C (Divide and Conquer). D&C means for questions that are divisible, we can divide them into plenty of subproblems, and solutions for subproblems can help us infer, and resolve the original problem.
- Randomly choose an item in the sequence .
- Set up 2 empty lists and .
- Let be the iterator, traverse throught the whole , For every smaller than , push it into . Otherwise push it into .
- Recursion : call this function again for and so that :
sort() = sort() + [] + sort()
P.S. Boundary conditions of sort() :
define sort():
if length of :
return
Time Complexity
~
Average complexity of quick sort is .
However, worst case happens if we keep selevting the smallest or the biggest item as .
Implementation
Merge Sort - 合併排序
Operations
Similar to quick sort, merge-sort uses D&C and recursion likewisely.
- Divide sequence into two same-length subsequence and .
- Recursion : call sort() again to sort the two parts.
- Combine and together. -> Finish!
sort() = merge(sort() + sort())
P.S. Definition of sort() :
define sort():
if length of :
return
Divide into and
Sort() and Sort()
sorted_ = Merge(, )
return sorted_
Time Complexity
Implementation
Heap Sort - 堆積排序
Features of heap
- Heap is a binary tree.
- parent node , it is always smaller than every node on its child tree.
- From 2, it's very clear that the root node is the smallest node in a heap.
Operations
- Create an empty list .
- Use given data to make a heap.
- Take out root node, push it into
- Refresh the whole heap.
- Repeat 3 - 4 until all nodes are popped out i.e. the list forms a sorted sequence.
Time Complexity