选择排序(Selection-sort):是一种简单直观的排序算法。它的工作原理:选择前面n-1个数中的最大值,和当前队尾数据交换,因为要交换最大值,所以要记录最大值位置的索引。首先在未排序序列中找到最大元素,存放到排序序列的起始位置,然后,再从剩余未排序元素中继续寻找最大元素,然后放到已排序序列的末尾。以此类推,直到所有元素均排序完毕。
最坏时间复杂度:
平均时间复杂度:
最好时间复杂度:
空间复杂度:
稳定性:不稳定
程序代码:
#include<iostream>
using namespace std;
void print(int a[], int n)
{
for(int j= 0; j<n; j++)
{
cout<<a[j] <<" ";
}
cout<<endl;
}
void selectSort(int a[], int len)
{
int minindex, temp;
for(int i = 0; i<len-1;i++)
{
minindex = i;
for(int j = i+1; j<len; j++)
{
if(a[j]<a[minindex])
minindex = j;
}
temp = a[i];
a[i] = a[minindex];
a[minindex] = temp;
}
}
int main()
{
int a[10] = {8,1,9,7,2,4,5,6,10,3};
cout<<"初始序列:";
print(a,10);
selectSort(a,10);
cout<<"排序结果:";
print(a,10);
system("pause");
}