java - selectionSort 程序中的交换功能问题
问题描述
如果我输入这些代码行,该程序将按我的预期工作:
temp = arr[x];
arr[x] = arr[y];
arr[y] = temp;
下selectionSort
功能,但不带swap功能。
这是我的代码:
class selectionSort {
public static void printArray(int[] arr) {
for (int x = 0; x < arr.length; x++) {
System.out.print("[" + arr[x] + "],");
}
System.out.println();
}
public static void selectionSort(int[] arr) {
for (int x = 0; x < arr.length - 1; x++) {
for (int y = x + 1; y < arr.length; y++) {
if (arr[x] > arr[y]) {
swap(arr[x], arr[y]); // this is the line that doesn't work
// int temp = arr[x];
// arr[x] = arr[y];
// arr[y] = temp;
}
}
}
System.out.println();
}
public static void swap(int x, int y) {
int temp = x;
x = y;
y = temp;
}
public static void main(String[] args) {
int[] arr = new int[] {
32,
213,
432,
21,
2,
5,
6
};
printArray(arr);
selectionSort(arr);
printArray(arr);
}
}
谁能解释为什么,或者给我一些提示?
谢谢!
解决方案
Java 不发送变量引用。它会复制该值,这就是为什么原始值不会更改的原因。因此,您需要从交换函数返回交换后的值。
推荐阅读
- c++ - C++ 令牌处理程序
- ios - 使用模拟器测试 CarPlay 音频
- azure - 当所有链接的子工作项满足特定条件时更改 Azure DevOps 父工作项状态?
- php - 格式为 YYYYMMDDTHHiiss 的两个日期之间的差异
- excel - VBA将值输入循环内过滤数据的前X个可见单元格
- c# - .NET Core 控制台应用程序 - 未在运行时设置适当的基于 appsettings 的环境变量
- android - 更改列表排序时,Android Compose LazyColum 渲染问题
- c# - System.ArgumentException: '路径中有非法字符。使用 C# 删除文件时
- python-3.x - 相对导入 python3 错误:尝试在没有已知父包的情况下进行相对导入
- android - 如何从以下 ROOM 数据库查询结果中提取 INT?