如何对并行数组升序排序并保持一致性以获取最值条目
并行数组排序与最值获取(Java实现)
需求说明
我有两个并行数组:一个String类型的产品数组,一个int类型的价格数组。需要对它们进行升序排序,同时保持数组元素的对应关系,还要能获取价格最高和最低的对应产品条目。以下是未完成的Java代码,需要实现相关方法:
package sortparallelarray; import javax.swing.JOptionPane; public class SortParallelArray { static String product[] = {"chips", "sweets", "juice", "cookies", "ice cream", "chocolate"}; static int price[] = {5, 3, 7, 6, 9, 8}; public static void main(String[] args) { // 先展示原始未排序的内容 displayArrays(formatDisplay()); // 展示最贵产品 displayArrays(getGreatestElementInPriceArray()); // 展示最便宜产品 displayArrays(getSmallestElementInPriceArray()); } public static void displayArrays(String displayable) { JOptionPane.showMessageDialog(null, displayable); } public static String formatDisplay() { String result = ""; for (int i = 0; i < price.length; i++) { result += "Product : " + product[i] + " Price : R" + price[i] + "\n"; } return result; } public static void sortArraysInAscendingNumericalOrder() { // 冒泡排序实现,同步维护两个数组的对应关系 for (int i = 0; i < price.length - 1; i++) { for (int j = 0; j < price.length - i - 1; j++) { if (price[j] > price[j + 1]) { // 交换价格数组元素 int tempPrice = price[j]; price[j] = price[j + 1]; price[j + 1] = tempPrice; // 同步交换产品数组对应位置的元素 String tempProduct = product[j]; product[j] = product[j + 1]; product[j + 1] = tempProduct; } } } } public static String getGreatestElementInPriceArray() { sortArraysInAscendingNumericalOrder(); String greatestElement = "Most expensive product\n\n"; // 升序排序后,最后一个元素为价格最高项 greatestElement += "Product : " + product[product.length - 1] + " Price : R" + price[price.length - 1]; return greatestElement; } public static String getSmallestElementInPriceArray() { sortArraysInAscendingNumericalOrder(); String smallestElement = "Cheapest product\n\n"; // 升序排序后,第一个元素为价格最低项 smallestElement += "Product : " + product[0] + " Price : R" + price[0]; return smallestElement; } }
关键实现说明
- 排序逻辑:采用冒泡排序,在交换价格数组元素的同时,同步交换产品数组对应索引的元素,确保产品和价格的对应关系不会断裂。
- 最值获取:升序排序完成后,价格数组首元素对应最便宜产品,尾元素对应最贵产品,直接取对应位置的元素即可。
- 代码修正:修复了原方法中
Cheapest pruduct的拼写错误,同时在main方法中补充了调用最值方法的逻辑,让功能可以完整运行。
内容的提问来源于stack exchange,提问作者Venus Mthethwa
相关产品推荐
相关产品推荐

