为什么我的交换方法不起作用?

时间:2015-02-27 15:06:52

标签: java swap

我已经成功写了一个Bubblesort课程。现在我试图打破功能,使代码更清洁。这是工作代码:

public class BubbleSortTest {

    public static void main(String[] args) {
        int[] array = {93, 60, 65, 45, 50};
        bubbleSort(array);
        printArray(array);
    }

    public static int[] bubbleSort(int[] array) {
        for(int i = 0; i < array.length - 1; i++) {
            for(int j = 0; j < array.length - 1 - i; j++) {
                if(array[j] < array[j + 1]) {
                    int temp = array[j];
                    array[j] = array[j + 1];
                    array[j + 1] = temp;
                 }
             }
         }
         return array;
    }

    public static void printArray(int[] array) {
        for(int i = 0; i < array.length; i++) {
            System.out.print(array[i] + " ");
        }
    }
}

对于这个例子,我想在bubbleSort函数中使用if语句的功能并使其成为自己的交换函数。所以我想要的代码看起来像:

public class BubbleSortTest {

    public static void main(String[] args) {
        int[] array = {93, 60, 65, 45, 50};
        bubbleSort(array);
        printArray(array);
    }

    public static int[] bubbleSort(int[] array) {
        for(int i = 0; i < array.length - 1; i++) {
            for(int j = 0; j < array.length - 1 - i; j++) {
                if(array[j + 1] > array[j]) {
                    swap(array[j + 1], array[j]);
                }
             }
         }
         return array;
    }

    public static void swap(int largerElement, int smallerElement) {
        int temp = largerElement;
        largerElement = smallerElement;
        smallerElement = temp;
    }

    public static void printArray(int[] array) {
        for(int i = 0; i < array.length; i++) {
            System.out.print(array[i] + " ");
        }
    }
}

当我运行后一个代码时,swap基本上什么都不做。我认为解决这个问题的方法是创建一个非void函数来返回值,但是我不能在不将它们封装到对象中的情况下返回这两个值(如果我错了,请纠正我)。交换功能一定有问题。我可能遗漏了一些基本的东西。后一个代码有什么问题?

1 个答案:

答案 0 :(得分:3)

Java is Pass By Value。您的swap方法必须接收数组和要交换的索引而不是int变量:

public static void swap(int[] array, int index1, int index2) {
    int temp = array[index1];
    array[index1] = array[index2];
    array[index2] = temp;
}