如果我输入这些代码行,该程序将按我的预期工作:
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);
}
}
谁能解释为什么,或者给我一些提示?
跃然一笑
守着星空守着你
慕森王
相关分类