如何在交换算法中实现返回

时间:2017-09-20 15:50:56

标签: java algorithm swap

我正在编写代码来实现一个交换,它将偶数索引上的所有元素放在小于或等于它们的邻居,奇数索引的所有元素都大于或等于它们的邻居。我需要在重新排列方法的最后给出一个return语句,但由于没有if else语句,我有点不知道该怎么做。任何帮助将不胜感激!

public class Problem3 {

public static boolean rearrange(int[] A)
{
    /*
Input: an array, A, of n sorted integers (positive, negative, or 0) that 
A[0] <= A[1] <= A[2] <=…A[n-2] <= A[n-1]

Output: re-arrange elements in A such that: 
Element at even position (i.e., A[0], A[2]) are less than or equal to both of its neighbors
Element at odd position (i.e., A[1], A[3]) are greater than or equal to both of its neighbors

A[0] <= A[1] >= A[2] <= A[3] >= A[4] <= A[5]…

Design an algorithm that solves this problem in O(n) time.

     */
    for (int i=1; i<A.length-1;){
        swap(A,A[i],A[i+1]);
    }

}

public static void swap(int[] A, int i, int j){
    int temp = A[i];
    A[i] = A[i+1];
    A[i+1] = temp;
}

public static void main(String[] args) {

    int[] A = {13, 20, 45, 69, 78, 100, 127, 155};

    System.out.println("Before:");

    for(int i=0; i < A.length; i++){

        System.out.print(A[i]+" ");
    }

    rearrange(A);

    System.out.println("After:");

    for(int i=0; i < A.length; i++){

        System.out.print(A[i]+" ");
    }



}

}

2 个答案:

答案 0 :(得分:0)

从我的角度来看,只要方法无法重新排列数组,就可以返回false。例如,如果某些合同被违反,可能就是这样。在你的任务中,我看到两个合同:

  • 输入不应为null
  • 输入数组应该排序。

在这种情况下,您的方法可能如下所示:

public static boolean rearrange(int[] A) {
    if (A == null || !isSorted(A)) {
        return false;
     }

     .... rearranging algorithm here
     return true;
}

答案 1 :(得分:-1)

我认为使用循环交换数组是非常昂贵的,还有额外的指针变量J,因为如果你使用循环那么它会将复杂性提高到2N。

循环将像((N + 1)+ N)一样执行,这意味着2N。

我相信用recursion投入资金将是有利的,下面我分享了我尝试递归的相同内容。但是返回应该独立于基本调用,验证可以在调用工作函数的实际逻辑之前自行完成。

public class Problem3 {

    /*
     * Input: an array, A, of n sorted integers (positive, negative, or 0) that
     * A[0] <= A[1] <= A[2] <=…A[n-2] <= A[n-1]
     * 
     * Output: re-arrange elements in A such that: Element at even position
     * (i.e., A[0], A[2]) are less than or equal to both of its neighbors
     * Element at odd position (i.e., A[1], A[3]) are greater than or equal to
     * both of its neighbors
     * 
     * A[0] <= A[1] >= A[2] <= A[3] >= A[4] <= A[5]…
     * 
     * Design an algorithm that solves this problem in O(n) time.
     * 
     */
    public static int[] swap(int[] A, int i) {
        if (i < A.length - 1) {
            int temp = A[i];
            A[i] = A[i + 1];
            A[i + 1] = temp;
            i = i + 1;
            swap(A, i);
        }
        return A;
    }

    public static void main(String[] args) {

        int[] A = { 13, 20, 45, 69, 78, 100, 127, 155 };

        System.out.println("Before:");

        for (int i : A) {

            System.out.print(i + " ");
        }

        System.out.println("\nAfter:");

        for (int i : swap(A, 0)) {

            System.out.print(i + " ");
        }

    }

}