【问题标题】:Selection Sort Gone Wrong选择排序出错
【发布时间】:2015-11-30 07:28:44
【问题描述】:

我正在尝试使用数组上的可比较进行选择排序。我不确定为什么它不起作用。如果有人可以看一下并帮助我找到不起作用的地方,那就太好了!谢谢!

public static Comparable[] no = new Comparable[100];

public static Comparable[] gen1()
{
    Random random = new Random();
    for(int i=0;i<no.length;i++)
    {
        no[i] =random.nextInt();
    }
    return no;
}   

public static Comparable[] selectionSort (Comparable no[])
   {
      int min;
      Comparable temp;

      for (int index = 0; index < no.length-1; index++)
      {
         min = index;
         for (int scan = index+1; scan < no.length; scan++)
            if (no[scan].compareTo(no[min]) < 0)
               min = scan;
         temp = no[min];
         no[min] = no[index];
         no[index] = temp;
      }
      return no;
   }

public static void main(String[] args)
{
    System.out.println("Original Array:");
    System.out.println(Arrays.toString(gen1()));
    System.out.println("Sorted Array:");
    System.out.println(selectionSort(no));

}

【问题讨论】:

  • 我刚刚试用了您的代码,排序似乎对我来说很好。我不得不将打印排序数组的行更改为System.out.println(Arrays.toString(selectionSort(no))); 这对您不起作用吗?如果没有,你能具体说明什么不起作用吗?

标签: java arrays sorting selection


【解决方案1】:

你没有说明你的问题是什么,但是在 main 的最后一行你应该这样做

  System.out.println(Arrays.toString(selectionSort(no)));

在我看来,输出已排序。

【讨论】:

  • 啊!谢谢!它总是最明显的事情!
猜你喜欢
  • 2019-04-24
  • 2013-04-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-07
  • 1970-01-01
  • 1970-01-01
  • 2019-04-10
相关资源
最近更新 更多