The program works as I expected if I put these lines of code:
temp = arr[x];
arr[x] = arr[y];
arr[y] = temp;
under the selectionSort
function, but not with the swap function.
Here's my code:
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);
}
}
Can anyone explain why, or give me some hints?
Thank you!