首页 > 代码库 > 排序算法之选择排序
排序算法之选择排序
选择排序定义:每一趟从待排序的数据元素中选出最小(或最大)的一个元素,顺序放在已排好序的数列的最后,直到全部待排序的数据元素排完。 选择排序是不稳定的排序方法。
class Program{ static void Main(string[] args) { int[] array = new[] { 234, 632, 23, 643, 2, 6, -2, 423, 2342 }; Console.WriteLine("排序前:"); Console.WriteLine(string.Join(",", array)); SelectSort(array); Console.WriteLine("排序后:"); Console.WriteLine(string.Join(",", array)); Console.ReadKey(); } /// <summary> /// 选择排序 /// </summary> /// <param name="sources">目标数组</param> private static void SelectSort(int[] sources) { for (int i = 0, len = sources.Length - 1; i < len; i++) { // 假设最小值索引 int minIndex = i; // 循环遍历一遍找到最小值的索引 for (int j = i + 1; j < len; j++) { // 如果最小值比其他元素大,重新设置最小值的索引 if (sources[minIndex] > sources[j]) { minIndex = j; } } // 临时变量交换最小值的位置; int temp = sources[i]; sources[i] = sources[minIndex]; sources[minIndex] = temp; } }}
排序算法之选择排序
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。