算法4的c++实现——选择排序

一、选择排序简介

选择排序(Selection sort)是一种简单直观的排序算法。
它的基本思想是:首先在未排序的数列中找到最小(or最大)元素,然后将其存放到数列的起始位置;接着,再从剩余未排序的元素中继续寻找最小(or最大)元素,然后放到已排序序列的末尾。以此类推,直到所有元素均排序完毕。

二、 选择排序的时间复杂度和稳定性

选择排序时间复杂度
选择排序的时间复杂度N2)。
假设被排序的数列中有N个数。遍历一趟的时间复杂度是O(N),需要遍历多少次呢?N-1!因此,选择排序的时间复杂度是O(N2)。

选择排序稳定性
选择排序是稳定的算法,它满足稳定算法的定义。
算法稳定性 – 假设在数列中存在a[i]=a[j],若在排序之前,a[i]在a[j]前面;并且排序之后,a[i]仍然在a[j]前面。则这个排序算法是稳定的!

三、C++代码实现

1.实现代码

//Sort.h
#include<vector>
using namespace std;

template <typename T>
bool lessthan(const T &a, const T &b)
{
	return a < b;
}

template <typename T>
void exch(T &a, T &b)
{
	T temp = a;
	a = b;
	b = temp;
}

template <typename T>
void show(const vector<T> &a)
{
	for (auto tmp : a)
		cout << tmp<<" ";
}

template <typename T>
bool isSorted(const vector<T> &a)
{
	int cnt = a.size();
	for (int i = 0; i < cnt-1; i++)
	{
		if (a[i] > a[i + 1])
			return false;
	}
	return true;
}

template <typename T>
void read(vector<T> &v, const string s)
{
	ifstream data(s); //待读取文件的目录
	string line;
	while (getline(data, line)) {
		stringstream ss; //输入流
		ss << line; //向流中传值
		if (!ss.eof()) {
			int temp;
			while (ss >> temp) //提取int数据
				v.push_back(temp); //保存到vector
		}
	}
}

template <typename T>
void SelectionSort(vector<T> &a)
{
	int cnt = a.size();
	for (int i = 0; i < cnt; i++)
	{
		int min = i;
		for (int j = i + 1; j < cnt; j++)
		{
			if (!lessthan(a[min], a[j]))
			{
				min = j;
			}
		}
		exch(a[min], a[i]);
	}
}

2.用例代码

#include<iostream>
#include<fstream>
#include<sstream>
#include<algorithm>
#include<string>
#include<vector>
#include<time.h>
#include"Sort.h"
using namespace std;

int main()  
{
	clock_t start, finish;
	double time=0; // CLOCKS_PER_SEC;
	vector<int> vec;
	read(vec, "4Kints.txt");
	cout << vec.size()<<endl;
	for (int i = 0; i < 10; i++)
	{
		start = clock();   //测试程序段花费的时间
		
		SelectionSort(vec); 
		//InsertionSort(vec);
		//ShellSort(vec);
		//MergeSort(vec);
		//QuickSort(vec);
		
		finish = clock();
		time += (double)(finish - start);
		cout << isSorted(vec) << endl;
		random_shuffle(vec.begin(), vec.end());
	}
	cout << "运行时间是" << time<<endl;
	system("pause");
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值