使两种排序算法都将值按降序排列。然后创建驱动器class来测试两种算法
Make both sorting algorithms put the values in descending order. Then create drive class to test the two algorithms
我对如何反转这些排序方法感到非常困惑。任何帮助,将不胜感激。
我已经查找并尝试进行研究,但找不到与此类可比列表有关的任何内容。
public class Sorting
{
public static void selectionSort(Comparable[] list)
{
int min;
Comparable temp;
for (int index = 0; index < list.length-1; index++)
{
min = index;
for (int scan = index+1; scan < list.length; scan++)
if (list[scan].compareTo(list[min]) < 0)
min = scan;
temp = list[min];
list[min] = list[index];
list[index] = temp;
}
}
public static void insertionSort(Comparable[] list)
{
for (int index = 1; index < list.length; index++)
{
Comparable key = list[index];
int position = index;
while (position > 0 && key.compareTo(list[position-1]) < 0)
{
list[position] = list[position-1];
position--;
}
list[position] = key;
}
}
}
我想如果你改变:
if (list[scan].compareTo(list[min]) < 0)
到
if (list[scan].compareTo(list[min]) > 0)
它将以相反的顺序排序。
int compareTo(T o)
Compares this object with the specified object for order. Returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.
我对如何反转这些排序方法感到非常困惑。任何帮助,将不胜感激。 我已经查找并尝试进行研究,但找不到与此类可比列表有关的任何内容。
public class Sorting
{
public static void selectionSort(Comparable[] list)
{
int min;
Comparable temp;
for (int index = 0; index < list.length-1; index++)
{
min = index;
for (int scan = index+1; scan < list.length; scan++)
if (list[scan].compareTo(list[min]) < 0)
min = scan;
temp = list[min];
list[min] = list[index];
list[index] = temp;
}
}
public static void insertionSort(Comparable[] list)
{
for (int index = 1; index < list.length; index++)
{
Comparable key = list[index];
int position = index;
while (position > 0 && key.compareTo(list[position-1]) < 0)
{
list[position] = list[position-1];
position--;
}
list[position] = key;
}
}
}
我想如果你改变:
if (list[scan].compareTo(list[min]) < 0)
到
if (list[scan].compareTo(list[min]) > 0)
它将以相反的顺序排序。
int compareTo(T o)
Compares this object with the specified object for order. Returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.