- stable sorting : 相同的值排序後順序皆一樣
- unstable sorting : 相同的值排序後順序可能會不一樣
# 初階排序
排序演算法 | #include <iostream> |
| #include <vector> |
| #include <algorithm> |
| |
| using namespace std; |
| |
| |
| void bubbleSort(vector<int>& arr) { |
| int n = arr.size(); |
| for (int i = 0; i < n - 1; i++) { |
| for (int j = 0; j < n - i - 1; j++) { |
| if (arr[j] > arr[j + 1]) { |
| swap(arr[j], arr[j + 1]); |
| } |
| } |
| } |
| } |
| |
| |
| |
| |
| void selectionSort(vector<int>& arr) { |
| int n = arr.size(); |
| for (int i = 0; i < n - 1; i++) { |
| int minIndex = i; |
| for (int j = i + 1; j < n; j++) { |
| if (arr[j] < arr[minIndex]) { |
| minIndex = j; |
| } |
| } |
| swap(arr[i], arr[minIndex]); |
| } |
| } |
| |
| |
| |
| |
| |
| void insertionSort(vector<int>& arr) { |
| int n = arr.size(); |
| for (int i = 1; i < n; i++) { |
| int key = arr[i]; |
| int j = i - 1; |
| while (j >= 0 && arr[j] > key) { |
| arr[j + 1] = arr[j]; |
| j--; |
| } |
| arr[j + 1] = key; |
| } |
| } |
| |
| int main() { |
| vector<int> arr = {5, 2, 8, 3, 1}; |
| |
| |
| bubbleSort(arr); |
| cout << "Bubble Sort: "; |
| for (int num : arr) { |
| cout << num << " "; |
| } |
| cout << endl; |
| |
| |
| arr = {5, 2, 8, 3, 1}; |
| selectionSort(arr); |
| cout << "Selection Sort: "; |
| for (int num : arr) { |
| cout << num << " "; |
| } |
| cout << endl; |
| |
| |
| arr = {5, 2, 8, 3, 1}; |
| insertionSort(arr); |
| cout << "Insertion Sort: "; |
| for (int num : arr) { |
| cout << num << " "; |
| } |
| cout << endl; |
| |
| return 0; |
| } |
# Quick sort
| #include <iostream> |
| #include <vector> |
| |
| using namespace std; |
| |
| |
| |
| |
| |
| int partition(vector<int>& arr, int low, int high) { |
| int pivot = arr[high]; |
| int i = low - 1; |
| |
| for (int j = low; j < high; j++) { |
| if (arr[j] < pivot) { |
| i++; |
| swap(arr[i], arr[j]); |
| } |
| } |
| |
| swap(arr[i + 1], arr[high]); |
| return i + 1; |
| } |
| |
| void quickSort(vector<int>& arr, int low, int high) { |
| if (low < high) { |
| int pivotIndex = partition(arr, low, high); |
| |
| |
| quickSort(arr, low, pivotIndex - 1); |
| quickSort(arr, pivotIndex + 1, high); |
| } |
| } |
| int main() { |
| vector<int> arr = {5, 2, 8, 3, 1}; |
| |
| |
| cout << "快速排序結果:" << endl; |
| quickSort(arr, 0, arr.size() - 1); |
| for (int num : arr) { |
| cout << num << " "; |
| } |
| cout << endl; |
| |
| return 0; |
| } |
在快速排序中,我們使用 partition
函式將陣列分割為比主元小和比主元大的兩個子陣列。
然後,我們遞迴地對這兩個子陣列進行排序,直到排序完成。