选择排序出错
Selection Sort Gone Wrong
我正在尝试使用数组上的可比较对象进行选择排序。我不确定为什么它不起作用。如果有人可以看一下并帮助我找到不起作用的地方,那就太好了!谢谢!
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));
}
你没有说明你的问题是什么,但在 main 的最后一行你应该做
System.out.println(Arrays.toString(selectionSort(no)));
输出对我来说是有序的。
我正在尝试使用数组上的可比较对象进行选择排序。我不确定为什么它不起作用。如果有人可以看一下并帮助我找到不起作用的地方,那就太好了!谢谢!
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));
}
你没有说明你的问题是什么,但在 main 的最后一行你应该做
System.out.println(Arrays.toString(selectionSort(no)));
输出对我来说是有序的。