选择排序(Simple Selection Sort)的思想:是每一趟从待排的记录中选出关键字最小的记录,按顺序放在已排序的记录序列的最后,知道全部排完为止。
简单选择排序代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 简单选择排序
{
public class Selectionsort
{
public void Sort(int[]list)
{
for (int i = 0; i < list.Length; i++)
{
int k = i;
for (int j = i + 1; j < list.Length; j++)
{
if (list[k] >list[j])
k = j;
}
if (k != i)
{
int t = list[i];
list[i]= list[k];
list[k]= t;
}
}
}
}
class Program
{
static void Main(string[] args)
{
int[] iArry = new int[] {49,38,65,97,49,13,27,76 };
Selectionsort ii = new Selectionsort();
ii.Sort(iArry);
for(int i=0;i<iArry.Length;i++)
{
Console.Write("{0} ",iArry[i]);
}
}
}
}
时间复杂度分析:简单选择排序所需移动记录次数较少,最好情况下一次都不用移动;最坏情况下(逆序),移动3(n-1)次;
无论什么情况下,都需要进行比较,比较次数KCN为n(n-1)/2。故时间复杂度为O(n²)。
空间复杂度:仅仅需要一个辅助空间O(1)。