输入10个数字,应用选择排序算法用c#实现
输入10个数字,应用选择排序算法用c#实现
请用c#写出一个选择排序算法,要求输入10个整数,输出排序结果。
代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SelectSorter
{
class SelectSorter
{
private static int[] myArray;
private static int arraySize;
public static void Sort(int[] a)
{
myArray = a;
arraySize = myArray.Length;
SelectSort(myArray);
}
public static void SelectSort(int[] myArray)
{
int i, j, smallest;
for (i = 0; i < myArray.Length - 1; i++)//数据开始位置从0到最后第2个数据
{
smallest = i;//记录最小数据的下标
for (j = i + 1; j < myArray.Length; j++)//在剩下的数据中寻找最小数据
{
if (myArray[j] < myArray[smallest])
{
smallest = j;//如果有比它更小的,记录下标
}
}
//将最小数据和末排序的第一个数据交换
Swap(ref myArray[i], ref myArray[smallest]);
}
}
private static void Swap(ref int left, ref int right)
{
int temp;
temp = left;
left = right;
right = temp;
}
public static void Main(string[] args)
{
int[] a = new int[] { 4, 2, 1, 6, 3, 6, 0, -5, 1, 1 };
SelectSorter.Sort(a);
for (int i = 0; i < a.Length; i++)
{
Console.WriteLine(a[i]);
}
}
}
}
原创文章转载请注明出处:云飞扬IT的blog





