【发布时间】:2015-12-09 06:02:30
【问题描述】:
我正在使用 Java 尝试使用合并排序对对象的价格进行排序。我已经在另一段完美运行的代码中使用了合并排序,并且我使用该模型为我正在处理的另一个项目开发合并排序。但是,当我运行程序时,它不会输出 Array 中的所有项目,最终会复制一些项目。
TestItem.java
public static void sortPrice(Item[] it, int low, int high) {
if (low == high) {
return;
}
int middle = (low + high)/2;
sortPrice(it, low, middle);
sortPrice(it, middle + 1, high);
merge(it, low, middle, high);
}
public static void merge(Item[] it, int l, int m, int h) {
System.out.println(h-l+1);
Item[] tmpItem = new Item[h - l + 1];
int index = 0;
int i = l, j = m + 1;
while (i <= m || j <= h) {
System.out.println(m);
if (i > m) {
tmpItem[index] = it[j];
j++;
} else if (j > h) {
tmpItem[index] = it[i];
i++;
} else if (it[i].getPrice() > it[j].getPrice()) {
tmpItem[index] = it[i];
i++;
} else {
tmpItem[index] = it[j];
j++;
}
index++;
}
for (int k = l; k <= h; k++) {
it[k] = it[k - l];
}
}
当我运行将数组打印到控制台的方法 printInventory() 时,我希望看到如下所示的输出。
预期产量(按价格从高到低排序):
1201: Wrench Sets Quantity Available: 55 Price: $80.0
1500: Ceiling Fans Quantity Available: 100 Price: $59.0
1034: Door Knobs Quantity Available: 60 Price: $21.5
1600: Levels Quantity Available: 80 Price: $19.99
1011: Air Filters Quantity Available: 200 Price: $10.5
1101: Hammers Quantity Available: 90 Price: $9.99
实际输出:
1201: Wrench Sets Quantity Available: 55 Price: $80.0
1034: Door Knobs Quantity Available: 60 Price: $21.5
1600: Levels Quantity Available: 80 Price: $19.99
1201: Wrench Sets Quantity Available: 55 Price: $80.0
1034: Door Knobs Quantity Available: 60 Price: $21.5
1600: Levels Quantity Available: 80 Price: $19.99
项目在 Item.java
中声明对不起,如果我犯了语法错误或引起混淆。我还在学习 Java 编程语言。感谢您的所有帮助!
【问题讨论】: