voidswap(int *a, int *b){ int temp = *a; *a = *b; *b = temp; }
通常測試排序用的會是陣列形式:
氣泡排序 (Bubble Sort)
1 2 3 4 5 6 7 8
voidBubble_Sort(int *array, int len){ for (int i = 0; i < len - 1; ++i) { for (int j = 0; j < len - 1 - i; ++j) { if (array[j] > array[j + 1]) swap(&array[j], &array[j + 1]); } } }
選擇排序 (Selection Sort)
1 2 3 4 5 6 7 8 9 10
voidSelection_Sort(int *array, int len){ for (int i = 0; i < len - 1; ++i) { int min_index = i; for (int j = i + 1; j < len; ++j) { if (array[min_index] > array[j]) min_index = j; } swap(&array[i], &array[min_index]); } }
插入排序 (Insertion Sort)
1 2 3 4 5 6 7 8 9 10 11
voidInsertion_Sort(int *array, int len){ for (int i = 1; i < len; ++i) { int key = array[i]; int j = i - 1; while (array[j] > key && j >= 0) { array[j + 1] = array[j]; j--; } array[j + 1] = key; } }