原理:扫描整个列表,找出最小(或最大)元素,然后将最小(或最大)元素与第一个元素交换位置。从第二个元素开始扫描列表,找出n-1个元素中的最小(或最大)元素,将最小(或最大)元素与第二个元素交换位置,如此类推,做n-1遍后排序结束
例题:对序列 {89,45,68,90,29,34,17}用选择排序 算法进行排序
第1遍: {89,45,68,90,29,34,17} //求最小元素
{17,45,68,90,29,34,89} //交换
第2遍: {17,45,68,90,29,34,89}
{17,29,68,90,45,34,89}
第3遍: {17,29,68,90,45,34,89}
{17,29,34,90,45,68,89}
第4遍: {17,29,34,90,45,68,89}
{17,29,34,45,90,68,89}
第5遍: {17,29,34,45,90,68,89}
{17,29,34,45,68,90,89}
第6遍: {17,29,34,45,68,90,89}
{17,29,34,45,68,89,90} //排序结束
伪代码:
SelectionSort(A[0..n-1])
for i=0 to n-2 do
min=i
for j=i+1 to n-1 do
if A[j]<A[min]
min=j
swap A[i] and A[min]
C++:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
#include<iostream> #include<time.h> #include<iomanip> using namespace std; const int N=10; int main() { int a[N],i,j,temp,b; srand ( time (NULL)); for (i=0;i<N;i++) a[i]= rand ()%100; for (i=0;i<N;i++) cout<<setw(3)<<a[i]; cout<<endl; for (i=0;i<N-1;i++)//有N-1趟 { temp=i; for (j=i+1;j<N;j++)//每一趟选择最小的排在a[i]处 { if (a[temp]>a[j]) temp=j; } if (i!=temp) { b=a[temp]; a[temp]=a[i]; a[i]=b;} } for (i=0;i<N;i++) cout<<setw(3)<<a[i]; cout<<endl; } |