這個程式會讀取使用者輸入的六個整數,使用簡單的選擇排序法對它們進行排序,然後輸出排序後的結果。選擇排序是一種簡單的排序算法,它的工作原理是:首先找到數列中的最小(或最大)元素,放到數列的起始位置,然後再從剩餘的元素中找到最小(或最大)元素,放到已排序序列的末尾。以此類推,直到所有元素均排序完畢。
c
Copy code
#include <stdio.h>
void sortIntegers(int arr[], int size) {
for (int i = 0; i < size - 1; i++) {
// 尋找最小元素的索引
int minIndex = i;
for (int j = i + 1; j < size; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j;
}
}
// 交換當前元素與最小元素
if (minIndex != i) {
int temp = arr[i];
arr[i] = arr[minIndex];
arr[minIndex] = temp;
}
}
}
int main() {
int numbers[6];
printf("請輸入六個整數:\n");
for (int i = 0; i < 6; i++) {
scanf("%d", &numbers[i]);
}
sortIntegers(numbers, 6);
printf("排序後的整數為:\n");
for (int i = 0; i < 6; i++) {
printf("%d ", numbers[i]);
}
printf("\n");
return 0;
}
這個程式首先定義了一個 sortIntegers 函式來實現選擇排序算法,然後在 main 函式中讀取用戶輸入的六個整數,呼叫 sortIntegers 函式進行排序,最後輸出排序後的結果。請注意,當使用 scanf 函式讀取用戶輸入時,用戶應該輸入六個整數並用空格隔開。