基本思想
选择排序开始的时候,扫描整个序列,找到整个序列的最小记录和序列中的第一个记录交换,从而将最小记录放到它在有序区的最终位置上,然后再从第二个记录开始扫描序列,找到n-1个序列中的最小记录,再和第二个记录交换记录。
一般地,第
i
i
趟排序从第个记录开始扫描序列,在
n−i+1(1≤i≤n−1)
n
−
i
+
1
(
1
≤
i
≤
n
−
1
)
记录中找到关键码最小的记录,并和第
i
i
个记录交换作为有序序列的第个记录。如下图所示:
选择排序算法C语言描述
void SelectSort(int r[],int n)
{
int i,j,index;
for(i=0;i<n-1;i++) //数组下标从0开始,对n个记录进行n-1趟排序
{
index=i; //查找最小值
for(j=i+1;j<n;j++) //在无序区中找最小记录
{
if(r[j]<r[index])
index=j;
}
if(index!=i)
swap(&A[min],&A[i]); //若最小记录不在最终位置则交换
}
该算法的基本语句是内循环体中的比较语句r[j]<r[index]
,其执行次数为:
因此,选择排序算法的时间性能为 O(n2) O ( n 2 ) 。
简单选择排序举例
<初态> 49 38 65 97 76 49 13 27
<第1趟> 13 38 65 97 76 49 49 27
<第2趟> 13 27 65 97 76 49 49 38
<第3趟> 13 27 38 97 76 49 49 65
<第4趟> 13 27 38 49 76 97 49 65
<第5趟> 13 27 38 49 49 97 76 65
<第6趟> 13 27 38 49 49 65 76 97
<第7趟> 13 27 38 49 49 65 76 97
(每趟排序使有序区增加一个记录)
验证结果
源码
#include "stdafx.h"
#include<time.h>
#include<iomanip>
#include<iostream>
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;
cout << "原始序列为: "<<endl;
for (i = 0; i<N; i++)
cout << setw(3) << a[i];
cout << endl;
for (i = 0; i<N - 1; i++)
{
temp = i;
for (j = i + 1; j<N; j++)
{
if (a[temp]>a[j])
temp = j;
}
if (i != temp)
{
b = a[temp];
a[temp] = a[i];
a[i] = b;
}
}
cout << "经过选择排序后的序列为: "<<endl;
for (i = 0; i<N; i++)
cout << setw(3) << a[i];
cout << endl;
}