需要打印一个数组的值与我使用冒泡排序排序的数组的平行值
问题描述:
我有一个学校项目,我应该使用Java在BlueJ上制作租车应用程序。一方面,我有2个阵列,一个是价格,一个是汽车的名称。我必须按照的价格的降序排列打印的名称。我设法使用冒泡排序降序排列价格数组,但我无法弄清楚如何在排序价格数组时排列如何打印汽车的名称。请帮忙。需要打印一个数组的值与我使用冒泡排序排序的数组的平行值
String carModel[] = {"A", "B", "C"}; //Names of cars
int costPerDay[] = {100, 75, 250}; //Rental cost per day
for(int x = 0; x < costPerDay.length-1; x++) { //Sort the Cost Per Day Array in descending order using bubble sort
for(int j = x + 1; j < costPerDay.length; j++) {
if(costPerDay[x] < costPerDay[j]) {
int t = costPerDay[x];
costPerDay[x] = costPerDay[j];
costPerDay[j] = t;
}
}
}
这是代码片段。我需要按其相应成本的降序打印汽车名称名称。
在此先感谢!
答
String carModel[] = {"A", "B", "C"}; //Names of cars
int costPerDay[] = {100, 75, 250}; //Rental cost per day
for(int x = 0; x < costPerDay.length-1; x++){ //Sort the Cost Per Day Array in descending order using bubble sort
for(int j = x + 1; j < costPerDay.length; j++){
if(costPerDay[x] < costPerDay[j]){
int t = costPerDay[x];
String s = carModel[x];
costPerDay[x] = costPerDay[j];
costPerDay[j] = t;
carModel[x] = carModel[j];
carModel[j] = s;
}
}
}
for(int x = 0; x < carModel.length; x++){
System.out.println(carModel[i]);
}
+0
非常感谢!我在这样一件容易的事情上打破了我的头!只是在最后一部分,它不应该是'carModel.length-1',而是'carModel.length'只有 –
+0
你是对的,我纠正了它。 – Garlic
答
有一个技巧可以做到这一点。使用另一个指示顺序的数组。
String carModel[] = {"A", "B", "C"}; //Names of cars
int costPerDay[] = {100, 75, 250}; //Rental cost per day
// Here's the trick - use an order array.
int order[] = {0,1,2};
for(int x = 0; x < costPerDay.length-1; x++){ //Sort the Cost Per Day Array in descending order using bubble sort
for(int j = x + 1; j < costPerDay.length; j++){
if(costPerDay[order[x]] < costPerDay[order[j]]){
int t = order[x];
order[x] = order[j];
order[j] = t;
}
}
}
现在像我这里有costPerDay[order[x]]
可以打印使用carModel[order[i]]
。
'Arrays.toString()'? – dehasi
创建一个POJO和一个该类型的数组 - 然后对该数组进行排序。或者,每次交换'costPerDay' **也**交换'carModel'。 –