使用合并排序提示检查数组顺序(升序)

时间:2018-01-25 08:37:22

标签: recursion

问题: 编写一个递归方法flgIsSorted来检查给定数组(作为参数提供)是否按递增顺序排序。当且仅当数组按递增顺序排序时,该方法返回true。提示,当数组只有一个元素时,它会被排序。如果对前半部分进行排序,则对后半部分进行排序,并且后半部分的第一个元素不小于前半部分中的最后一个元素,则对该数组进行排序。您的初始方法只能使用一个参数 - 数组。该方法可以调用另一个带有其他参数的辅助方法。

public boolean flgIsSorted(int a[], int startIndex, int endIndex ){
    boolean result = false;
    if(startIndex < endIndex){
        int mid = (startIndex + endIndex)/2;
        flgIsSorted(a, startIndex, mid);
        flgIsSorted(a, mid+1, endIndex);
        result = check(a, startIndex, mid, endIndex);
    }
    return result;
}

public boolean check(int a[], int startIndex, int mid, int endIndex){

    //deal with left array
    //If array has odd number of elements, 
    //left array will be even number
    //and right array will be odd number
    int n1 = mid - startIndex + 1;

    // n1 is index, and we need n1 + 1 spots for copy array
    int L[] = new int[n1 + 1];

    //copy subarray A[p..q] into L[0..n1], 
    //i starts from the beginning of unsorted array
    for(int i = startIndex; i <= mid + 1; i++){
        //make sure copy to the index 0 of left array
        L[i - startIndex] = a[i];
    }
    L[n1] = Integer.MAX_VALUE;

    //deal with right array
    int n2 = endIndex - mid;
    int R[] = new int[n2 + 1];

    //copy subarray A[q+1..r] into R[0..n2]
    for(int j = mid + 1; j <=  endIndex; j++){
        //make sure start from the index 0 of right array
        R[j - (mid + 1)] = a[j];
    }
    R[n2] = Integer.MAX_VALUE;

    int i = 0;
    int j = 0;  
    boolean result = false;
    for(int k = startIndex; k <= endIndex; k++){
        if(L[i] < R[j]){
            //a[k] = L[i];
            i++;
            result = true;
            System.out.println("true in check");
        }else{
            //a[k] = R[j];
            j++;
            System.out.println("false in check");
            result = false;
        }
    }
    System.out.println("return in check final");
    return result;
}   

问题: 它总是返回true。

1 个答案:

答案 0 :(得分:0)

我想我今天早上才知道。至少输出是我现在想要的。

代码:

    public boolean flgIsSorted(int a[], int startIndex, int endIndex){
    boolean result = false;
    if(a.length == 1){
        result = true;
    }else{
        if(startIndex < endIndex){
            int mid = (startIndex + endIndex)/2;
            if(a[startIndex] <= a[mid + 1]){
                result = true;
            }else{
                result = false;
            }
            flgIsSorted(a, startIndex, mid);
            flgIsSorted(a, mid + 1, endIndex);
        }
    }
    return result;
}