一个简单的选择排序
c#吧
全部回复
仅看楼主
level 3
510420060 楼主
所谓选择排序就是在一堆数组中选出最大(最小值),然后让它和第i个交换位置,i从0到i.length循环。最后得到有序数组。我写了一个,但是有时候成功有时候不成功。请大家看看。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 选择排序
{
class Program
{
static int[] num = new int[10];
static int[] aa = { 342, 432, 543, 43, 32, 543, 654, 56, 7, 3 };
static void Main(string[] args)
{
/*
Console.WriteLine("请输入10个整数");
for (int i = 0; i < num.Length; i++)
{
Console.WriteLine("你输入的第" + (i+1) + "个数是");
int.TryParse(Console.ReadLine(), out num[i]);
}
*/
num = sortArr2(aa);
Console.WriteLine("排序后的顺序是");
for (int i = 0; i < num.Length; i++)
{
Console.Write(num[i] + "\t");
}
Console.ReadKey();
}
private static int[] sortArr2(int[] a)
{
//a[1,22,2]i是
正确的

//最开始假定最小值为a[0]
int max;
int a_;
int i = 0;//十个数都循环
int j;//开始比较的数的下标
for (; i < a.Length; i++)//length=3
{
max = a[i];//假设最大值,赋值
for (j = 1 + i; j < a.Length; j++)//和剩下的进行比较,找出最大值
{
if (a[j] > max)
max = a[j];
}
a_ = Array.IndexOf(a, max);//通过找到的最大数确定其位置
Console.WriteLine("a_的值是"+(a_+1)+"最大值是"+max);
a[i] = max + (a[a_] = a[i]) * 0;//让最大值a[a_]==max和当前的a[i]交换
}
return a;
}
}
}
测试用数组就不行
2014年10月28日 14点10分 1
level 10
IndexOf会返回首次出现的下标,请使用LastIndexOf
2014年10月28日 15点10分 2
我查了一下,发现这个IndexOf()和LastIndexOf()分别是从数组的前面查和后面查,并不影响啊。为甚么会出现这个错误
2014年10月29日 03点10分
回复 510420060 :详见楼下
2014年10月29日 11点10分
level 10
比如
1 2 3 2
扫一遍
1 ^ 2 3 2
再扫一遍
1 2 ^ 3 2
再扫一遍,现在问题来了
如果用IndexOf
把第一个2和3交换了,于是
1 3 2 ^ 2
然后……
1 3 2 2
如果用LastIndexOf
把最后一个2和3交换
1 2 2 ^ 3
然后……
1 2 2 3
OK?
2014年10月29日 11点10分 3
嗯,明白了,很感谢。只有一个小错误需要纠正,这个其实找的是最大值。。。但道理是一样的:如果从前面开始找,就会把原来排好的相同的值找出来,和目前的值进行交换,导致排序错误
2014年10月30日 13点10分
1