您的位置:首页 > 其它

八大排序算法之三选择排序—简单选择排序(Simple Selection Sort)

2016-09-19 22:52 567 查看
基本思想:

在要排序的一组数中,选出最小(或者最大)的一个数与第1个位置的数交换;然后在剩下的数当中再找最小(或者最大)的与第2个位置的数交换,依次类推,直到第n-1个元素(倒数第二个数)和第n个元素(最后一个数)比较为止。

简单选择排序的示例:

#include<iostream>
using namespace std;
const int N =1005;
void SelectSort(int a[],int );
void print(int a[],int num);
void swap(int &a,int &b);

int main()
{
int s
;
int T;
cin>>T;
while(T--)
{
int n;
cin>>n;
for(int j=0;j<n;j++)
cin>>s[j];
SelectSort(s,n);
print(s,n);
cout<<endl;
}
return 0;
}
void SelectSort(int arr[],int size)
{
int minIndex, maxIndex;
for (int i = 0; i < size / 2; i++) {
minIndex = i;
maxIndex = size-i-1;
for (int j = i; j < size - i ; j++) {

if (arr[j] > arr[maxIndex]) {
maxIndex = j;
//continue;
}
if (arr[j] < arr[minIndex]) {
minIndex = j;

}

}
if (maxIndex == i && minIndex == size - i - 1) {
//特殊交换位置一,当最大的交换位置和最小的交换位置都在最前面和最后面
swap(arr[maxIndex],arr[minIndex]);
}
else if (maxIndex == i) {
//特殊交换位置二,当最大的交换位置是最前面
// Swap(arr[n - i], arr[maxIndex])
swap(arr[size-i-1],arr[maxIndex]);

swap(arr[i], arr[minIndex]);
}
else if (minIndex == size - i - 1) {
//特殊交换位置三,当最小的交换位置是最后面
swap(arr[i], arr[minIndex]);
swap(arr[size - i-1], arr[maxIndex]);
}
else {
//除了上面三种特殊交换,就剩普通交换了,普通交换随便哪个先交换都行
swap(arr[i], arr[minIndex]);
swap(arr[size - i-1], arr[maxIndex]) ;
}
}
}
void swap(int &a,int& b)//交换元素
{
int temp;
temp=a;
a=b;
b=temp;
}
void print(int a[],int n)//输出数组元素
{
cout<<a[0];
for(int k=1;k<n;k++)
{
cout<<" "<<a[k];
}
}


View Code
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: