# C# 算法之选择排序

1、简介

2、C#实现

/// <summary>
/// 选择排序
/// </summary>
public class SelectctionSort
{
static void Main(string[] args)
{
var arr = new IComparable[] { 7,3,5,1,2,89,8 };
var result= Sorted(arr);
Array.ForEach(arr, Console.WriteLine);
Console.WriteLine("排序是否成功?{0}", IsSorted(result) ? "是" : "否");
Console.ReadKey();
}

/// <summary>
/// 选择排序Main方法
/// </summary>
/// <param name="array"></param>
/// <returns></returns>
public static IComparable[] Sorted(IComparable[] array)
{
int count = array.Length;
for (int i = 0; i < count; i++)
{
//假设每一轮外循环的第一个是最小的
int min = i;
for (int j = i + 1; j < count; j++)
if (Less(array[j], array[min])) min = j;
Exchange(array, i, min);
}
return array;
}

/// <summary>
/// 判断两个元素的大小
/// </summary>
/// <param name="a"></param>
/// <param name="b"></param>
/// <returns></returns>
private static bool Less(IComparable a, IComparable b)
{
var res = a.CompareTo(b);
return res < 0;
}

/// <summary>
/// 交换一轮循环后的结果
/// </summary>
/// <param name="array"></param>
/// <param name="i"></param>
/// <param name="min"></param>
private static void Exchange(IComparable[] array,int i,int min)
{
var temp = array[i];
array[i] = array[min];
array[min] = temp;
}

/// <summary>
/// 判断排序是否正确
/// </summary>
/// <param name="array"></param>
/// <returns></returns>
private static bool IsSorted(IComparable[] array)
{
for (int i = 1; i < array.Length; i++)
{
if (Less(array[i], array[i-1])) return false;
}
return true;
}
}

371 篇文章52 人订阅

0 条评论