asasaas121 2014-10-29 05:46 采纳率: 0%
浏览 1903

c#使用选择排序出错,有时会出现重复或者排错

选择排序是通过选取一组数中的最大值(最小值),然后将最大值(最小值)和数组首位的值相交换,然后再对除第一个值得剩下的数进行排序。请看看我写的
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;
}
}
}

  • 写回答

1条回答 默认 最新

  • feiyun0112 2014-10-29 05:58
    关注

    private static int[] sortArr2(int[] a)
    {
    //a[1,22,2]i是正确的
    //最开始假定最小值为a[0]
    int max;
    int a_=0;
    int i = 0;//十个数都循环
    int j;//开始比较的数的下标
    for (; i < a.Length - 1; i++) //length=3
    {

                max = a[i]; //假设最大值,赋值
                for (j = 1 + i; j < a.Length; j++) //和剩下的进行比较,找出最大值
                {
                    if (a[j] > max)
                    {
                        max = a[j];
                        a_ = j;
                    }
                }
    
                if (max != a[i])
                {
                    Console.WriteLine("a_的值是" + (a_ + 1) + "最大值是" + max);
                    a[i] = max + (a[a_] = a[i]) * 0;//让最大值a[a_]==max和当前的a[i]交换
                }
            }
            return a;
        }
    
    评论

报告相同问题?

悬赏问题

  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 spring后端vue前端
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题
  • ¥15 Visual Studio问题