(C++)数据结构排序---选择排序

选择排序基本思想:一个数组a有n个数据,首先对n个数据进行(n-1)次比较,可得该组数据最大值或最小值,把该值与第一个数据(a[0])交换位置;剩下的数据,按上述方法依次取得最大(小)值,即可获得有序数据。由上可知,共需进行(n-1)趟比较。需要两个辅助空间。比较次数为:n*(n-1)/2

平均情况的时间复杂度          最好情况的时间复杂度               最坏情况的时间复杂度         空间复杂度

         O(n^2)                                 O(n^2)                                        O(n^2)                        O(1)

原数据:18,23,15,3,8

第一趟:3,23,15,18,8

第二趟:3,8,15,18,23

第三趟:3,8,15,18,23

第四趟:3,8,15,18,23

第五趟:3,8,15,18,23

#ifndef _SELECTSORT_H
#define _SELECTSORT_H
#include<iostream>
using namespace std;

template<class Type>
void SelectSort(Type *a,int n)
{
	Type tem;
	int flag;
	for(int i=0;i<n-1;i++)
	{
		flag=i;
		for(int j=i+1;j<n;j++)
		{
    		if(a[j]<a[flag]) //由小到大排列;若换为>,则为由大到小排列
			{
				flag=j;
			}
    	}
    	if(flag!=i)
    	{
    		tem=a[flag];
    		a[flag]=a[i];
    		a[i]=tem;
		}
		for(int i=0;i<n;i++)
		cout<<a[i]<<" ";
		cout<<endl;				
	}
}
#endif 

测试代码:

#include<iostream>
#include"SelectSort.h"
using namespace std;
int main()
{
	int a[10]={18,23,15,3,8,54,12,54,76,100};
	for(int i=0;i<10;i++)
	cout<<a[i]<<" ";
	cout<<endl;
	SelectSort(a,10);
	for(int i=0;i<10;i++)
	cout<<a[i]<<" ";
	cout<<endl;
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_40951833/article/details/80756695