我正在尝试根据它们的值按降序对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,名称=镍]]
预期:[硬币[值= 1.0,名称=美元],硬币[值= 0.25,名称=季度],硬币[值= 0.1,名称=硬币],硬币[值= 0.05,名称=镍],硬币[值= 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;
}
}
1 回答
你可以在列表中引入数组,在对列表进行排序后最后再将这些参数引入数组,这比使用它们更容易
在类硬币中,介绍 public class Coin implements Comparable
你应该实现一个方法: CompareTo(Coin p) // p是一个例子
在此方法中介绍: return this.r-prueva.r; //您将在下一步中使用此步骤Comparable.Sort
例:
多数民众赞成...现在在你的 class 你可以创建一个方法或引入它来排序数组:
很容易......如果你想要,如果不能理解我的语言,我可以展示你需要的代码:
你的硬币类实现可比性可能是这样的......
您的 class CoinSelectionSorted可能如此......
我希望我能帮到你
好运