/*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; }
运行结果: