我正在尝试根据 Coin 对象的值按降序对它们的数组进行排序。我的 Coin 类中有一个 getValue() 方法。我的问题是最终结果根本没有排序。这就是我最终得到的。我似乎无法弄清楚我哪里出错了任何提示都会有所帮助
在我们排序之前:[Coin[value=0.25,name=quarter], Coin[value=0.01,name=penny], Coin[value=0.1,name=dime], Coin[value=1.0,name=dollar], Coin [值=0.05,名称=镍]]
预期:[Coin[value=0.25,name=quarter], Coin[value=0.01,name=penny], Coin[value=0.1,name=dime], Coin[value=1.0,name=dollar], Coin[value =0.05,名称=镍]]
我们排序后:[Coin[value=0.01,name=penny], Coin[value=0.1,name=dime], Coin[value=0.25,name=quarter], Coin[value=1.0,name=dollar], Coin [值=0.05,名称=镍]]
预期:[Coin[value=1.0,name=dollar], Coin[value=0.25,name=quarter], Coin[value=0.1,name=dime], Coin[value=0.05,name=nickel], Coin[value =0.01,姓名=便士]]
import java.util.Arrays;
/**
This class sorts an array of coins, using the selection sort
algorithm.
*/
public class CoinSelectionSorter
{
//
private Coin[] list;
/**
Constructs a selection sorter.
@param anArray the array to sort.
*/
public CoinSelectionSorter(Coin[] anArray)
{
list = anArray;
}
public String toString()
{
return Arrays.toString(list);
}
/**
Finds the largest coin in an array range.
@param from the first position in a to compare
@return the position of the largest coin in the
range a[from] . . . a[a.length - 1]
*/
public int maximumPosition(int from)
{
int max = from;
for(int i = 0; i < list.length-1; i++){
if(list[i].getValue() > list[max].getValue()){
max = i;
}
}
return max;
}
/**
Sorts an array.
*/
public void sort()
{
for(int i = 0; i < list.length -1; i++){
int max = maximumPosition(i);
swap(i, max);
}
}
/**
Swaps two entries of the array.
@param i the first position to swap
@param j the second position to swap
*/
public void swap(int i, int j)
{
Coin temp = list[i];
list[i] = list[j];
list[j] = temp;
}
}