/*A[1...n]爲一個有n個元素的數組,首先找到最小元素,將其存放在A[1]中, 而後找到剩下的n-1個元素中的最小元素,將其存放在A[2]中,重複此過程直至找到第二大元素*/ /*算法描述: 輸入: n個元素的數組A[1...n] 輸出:按非降序排列的數組A[1...n] for i <- 1 to n-1 k <- i for j <- i+1 to n {查找第i小的元素} if A[j] < A[k] then k <- j end for if k != i then 交換A[i]與A[k] end for */ #include<iostream> #define N 9 using namespace std; void selectSort(int A[], int n) { int k; int temp; //k表示每次找到的最小數的下標 for (int i = 0; i < n-1; i++) //控制次數,找n-1次 { k = i; for (int j = i+1; j < n; j++) { if (A[j] < A[k]) k = j; } if (i != k) //將最小數交換至前面 { temp = A[i]; A[i] = A[k]; A[k] = temp; } } for (int t = 0; t < n; t++) cout << A[t] << " "; cout << endl; } int main() { int A[N] = {20,3,6,1,87,46,12,5,2}; cout << "before sort: "; for (int i = 0; i < N; i++) cout << A[i] << " "; cout << endl; cout << "after sort:"; selectSort(A, N); return 0; }
運行結果:ios