我們首先需要複制ADATA到BDATA,然後在BDATA上進行排序。這樣可以保持ADATA的原始數據不變。
以下是一個C語言程序的示例,實現上述要求:
#include <stdio.h>
void selectionSort(int arr[], int n) {
int i, j, minIndex, temp;
for (i = 0; i < n - 1; i++) {
minIndex = i;
for (j = i + 1; j < n; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j;
}
}
// 交換最小元素和當前位置的元素
temp = arr[minIndex];
arr[minIndex] = arr[i];
arr[i] = temp;
}
}
int main() {
const int N = 5; // 假設數組的大小為5
int ADATA[N] = {5, 3, 4, 1, 2}; // 初始化數組,並賦予一些示例值
int BDATA[N]; // 用於存儲排序後的數組
// 複製ADATA到BDATA
for (int i = 0; i < N; i++) {
BDATA[i] = ADATA[i];
}
// 對BDATA進行選擇排序
selectionSort(BDATA, N);
printf("經過Selection Sort排序後的BDATA數組元素為:\n");
for (int i = 0; i < N; i++) {
printf("%d ", BDATA[i]); // 列印BDATA中的每個元素
}
printf("\n"); // 在列印完所有元素後換行
return 0;
}
這段代碼中,selectionSort函數實現了選擇排序算法,它接受一個整數數組和數組的大小作為參數。main函數中首先定義了原始數組ADATA並初始化了一些值,然後將ADATA的內容複製到BDATA。之後,BDATA使用selectionSort函數進行排序。最後,遍歷並列印BDATA中的所有元素,展示排序後的結果。