Yung-Sheng Lu
FEB 09, 2015
@NCKU-CSIE
Lecture 2
將數字放進循序性的資料結構
例如:陣列 (Array),鏈結串列 (Linked List)
使用有排序功能的資料結構
例如:Binary Heap,Binary Search Tree (BST)
選擇排序法 (Selection Sort)
插入排序法 (Insertion Sort)
氣泡排序法 (Bubble Sort)
合併排序法 (Merge Sort)
快速排序法 (Quick Sort)
Heap Sort
Counting Sort
Bucket Sort
Radix Sort
Flash Sort
void selection_sort(int arr[], int N) {
for (int i = 0; i < N - 1; ++i) {
int min_index = i;
for (int j = i + 1; j < N; ++j) {
if (arr[j] < arr[min_index])
min_index = j;
}
// Swap
swap(arr[i], arr[min_index]);
}
}
Average Case:
Extra Space:
void insertion_sort(int arr[], int N) {
for (int i = 2; i < N; ++i) {
int key = arr[i];
int j = i - 1;
while (j >= 0) {
if (key < arr[j])
arr[j + 1] = arr[j];
else
break;
--j;
}
// Insert
arr[j + 1] = key;
}
}
Average Case:
Extra Space:
void bubble_sort(int arr[], int N) {
for (int i = 0; i < N; ++i) {
for (int j = 0; j < N - i - 1; ++j) {
if (arr[j] > arr[j + 1])
swap(arr[j], arr[j + 1]);
}
}
}
Average Case:
Extra Space:
/* Divide */
void merge_sort(int arr[], int low, int high) {
if (high > low) {
merge_sort(arr, low, (low + high) / 2);
merge_sort(arr, (low + high) / 2 + 1, high);
merge(arr, low, high);
}
}
/* Merge */
void merge(int arr[], int low, int high) {
int sort[MAX], k = -1, mid = (low + high) / 2;
for (int i = low, j = mid + 1; i <= mid || j <= high) {
if (i > mid || arr[i] >= arr[j])
sort[++k] = arr[j++];
else if (j > high)
sort[++k] = arr[i++];
else
sort[++k] = arr[i++];
}
k = 0;
for (int i = low; i <= high; ++i)
arr[i] = sort[k++];
}
Average Case:
Extra Space:
PTC 程式設計競賽 - 月賽
CPE 大學生程式能力檢定 - 每學期二次
Google Code Jam
Facebook Hacker Cup