一.算法描述
选择排序算法的运作如下:
首先在未排序序列中找到最小(大)元素,存放到排序序列的起始位置,然后,再从剩余未排序元素中继续寻找最小(大)元素,然后放到已排序序列的末尾。以此类推,直到所有元素均排序完毕。
二.时间复杂度
1.最好情况:在输入的数组已经排序的情况下,对于选择排序,需要的比较次数为为(n-1)+(n-2)+...+1=n(n-1)/2,交换次数为n-1,因此,最好情况下,冒泡排序的时间复杂度为O(n^2).
2.最差情况:在输入逆序的数组的情况下,对于选择排序,需要的比较次数为为(n-1)+(n-2)+...+1=n(n-1)/2,交换次数为n-1,因此,最差情况下,冒泡排序的时间复杂度为O(n^2).
3.平均情况:在平均情况下的时间代价是最差情况下的一半,因此,平均情况下,插入排序的时间复杂度也为O(n^2).
三.空间复杂度
选择排序是in-place的排序方法,因此空间复杂度为O(1)。
四.C++实现
<span style="font-size:18px;">#include <iostream>
#include "Sort.h"
bool SelectionSort(std::vector<int>& Array)
{
// return false if the array is empty.
if (Array.empty())
{
std::cout << "The size of the Array is empty." << std::endl;
return false;
}
// return the origin array if there are only one element of the array
if (Array.size() == 1)
{
std::cout << "The size of the array is one." << std::endl;
return true;
}
int Size = Array.size();
for (int OuterIndex = 0; OuterIndex < Size; OuterIndex++)
{
int MinValueIndex = OuterIndex;
int MinValue = Array[MinValueIndex];
for (int InnerIndex = OuterIndex + 1; InnerIndex < Size; InnerIndex++)
{
if (MinValue > Array[InnerIndex])
{
MinValueIndex = InnerIndex;
MinValue = Array[MinValueIndex];
}
}
Array[MinValueIndex] = Array[OuterIndex];
Array[OuterIndex] = MinValue;
}
return true;
}</span>
五.参考文献
[1] Shaffer C A. Practical Introduction to Data Structure and Algorithm Analysis (C++ Edition)[J]. 2002.
[2] 科曼 and 金贵, 算法导论: 机械工业出版社, 2006.
[3] T. H. Cormen, C. E. Leiserson, R. L. Rivest, and C. Stein, "算法导论 (影印版)," ed: 北京: 高等教育出版社.
[4]http://zh.wikipedia.org/wiki/%E9%80%89%E6%8B%A9%E6%8E%92%E5%BA%8F
版权所有,欢迎转载,转载请注明出处,谢谢