我是否只是重写了两次,或者是否有更有效的方式 这样做呢?如何以与价格相同的模式(从低到高)对物品进行排序?
public class W14_3 {
public static void main(String [] args){
double[] price={73.25, 48.0, 345.0, 152.35, 196.50};
String[] items={"bag", "stationary", "books", "shoes","clothing"};
selectionSort(price , items);
for(int i = 0; i<price.length; i++)
System.out.println(price[i]);
for(int j=0; j<items.length; j++){
System.out.println(items[j]);
}
}
public static void selectionSort(double[] P , String[] I ){
for(int startIndex=0; startIndex <P.length-1; startIndex++)
{
double min = P[startIndex];
int indexOfMin = startIndex;
for(int j= startIndex +1; j< P.length; j++)
if(P[j] < min)
{
min =P[j];
indexOfMin=j;
}
P[indexOfMin] = P[startIndex];
P[startIndex] = min;
}
}
}
}
答案 0 :(得分:0)
考虑到你几乎就在那里,我建议你把你的数组变成一个数字和字符串是该类成员的类。 e.g。
public class someName {
public String getItem() {
return item;
}
public void setItem(String item) {
this.item = item;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
private String item;
private double price;
public someName(String item, double price){
this.item = item;
this.price = price;
}
}
现在进行选择排序,我们需要稍微改变一下。
public static void selectionSort(someName[] arr){
for(int i = 0; i < arr.length-1; i++){
int minIndex = i; // smallest element index
for(int j = i + 1; j < arr.length; j++){
if(arr[j].getPrice() < arr[i].getPrice()){ // find smallest element
if(arr[j].getPrice() < arr[minIndex].getPrice())
minIndex = j; // update smallest element index
}
}
if(i != minIndex){ // swap
someName temp = arr[minIndex];
arr[minIndex] = arr[i];
arr[i] = temp;
}
}
}
然后在你的主要方法中:
public static void main(String[] args) {
someName[] someIdentifier = new someName[5];
someIdentifier[0] = new someName("bag",73.25);
someIdentifier[1] = new someName("stationary",48.0);
someIdentifier[2] = new someName("books",345.0);
someIdentifier[3] = new someName("shoes",152.35);
someIdentifier[4] = new someName("clothing",196.50);
selectionSort(someIdentifier);
for (someName item : someIdentifier) {
System.out.println(item.getItem() + " : " + item.getPrice());
}
}
有关Selection Sort如何运作以及我为何如此行事的其他信息,请参阅Selection Sort上的上一篇文章。