java - 使用冒泡法对数组进行升序排序。然后其他数组位于不同的索引处
问题描述
该程序假定读取包含商品、代码和价格的文件。我将它输出到屏幕上以显示它在数组中的索引。例如 Item[0], Code[0] ,Price[0] 都通过每个可能的索引。该程序假设使用冒泡排序方法对 Code 值从小到大进行排序。到目前为止,我已经得到了正确的。我的问题是你如何让这三个方面都尊重变量。例如,如果 wine ,1298, 8.99 都在它们各自的索引 [3] 中,那么当将 Code 值放入冒泡排序时,它会交换到索引 [0]。你如何让价格和项目的索引也切换到索引[0]。那是我的问题。到目前为止,我们刚刚在课堂上学习了基本的 java,所以我还不知道任何高级的东西。
import java.io.File;
import java.util.Scanner;
import java.util.*;
public class test2 {
public static void main(String[] args) throws Exception {
File file = new File("C:\\Users\\Isiah\\Desktop\\xfiles.txt");
Scanner input = new Scanner(file);
System.out.println("Item \t Code \t Price");
String[] Item = new String[7];
int[] Code = new int[7];
double[] Price = new double[7];
int c = 0;
while (input.hasNext()) {
Item[c] = input.next();
Code[c] = input.nextInt();
Price[c] = input.nextDouble();
System.out.println(Item[c] + "\t" + Code[c] + "\t" + Price[c]);
c++;
}
input.close();
// Call Bubble Method
bubbleSort(Code, Item, Price);
System.out.println(" ");
System.out.println("Code \t Item \t Price");
for (int i = 0; i < Item.length; i++) {
System.out.println(Code[i]);
}
}
// Bubble Sort Method
static void bubbleSort(int Code[], String[] Item, double Price[]) {
int n = Code.length;
for (int i = 0; i < n - 1; i++)
for (int j = 0; j < n - i - 1; j++)
if (Code[j] > Code[j + 1]) {
// swap temp and score[i]
int temp = Code[j];
Code[j] = Code[j + 1];
Code[j + 1] = temp;
}
}
}
Item Code Price
beer 1357 12.99
apple 2357 0.5
bread 2123 1.25
wine 1298 8.99
pants 3009 6.99
sugar 2111 2.69
socks 3123 11.89
Code Item Price
1298
1357
2111
2123
2357
3009
3123
解决方案
使用您当前的代码,您将不得不交换所有数组中的项目。所以,当你交换Code[i]
and时Code[j]
,也交换Item[i]
and Item[j]
and Price[i]
and Price[j]
。
一种更面向对象的方法是定义一个类,其中包含Code
,Item
和Price
字段,例如Thing
:
class Thing {
int code;
String item;
double price;
}
然后对这些数组进行排序:Thing[]
.
推荐阅读
- jquery - 网站未正确调整到移动设备的大小(元值到位)
- python - 包含 if 语句的 while 循环的问题
- javascript - 如何让 webview findInPage() 在 Electron 中工作
- javascript - 如何 console.log 列表的一部分?
- swift - 颜色 rgb 初始化程序在 SwiftUI 中不能作为背景工作
- python - 从数据框中的文本列中选择唯一组合
- jquery - jQuery.getJSON() - Can get data from JSON
- android - 如何以编程方式从android中的html + css生成图像jpg?
- javascript - 使用 react / react-bootstrap / flexbox 居中图像
- java - 捕获 Ctrl+C 信号会引发异常“作业管理器已关闭”