【问题标题】:check array order(ascending) using hint of merge sort使用合并排序提示检查数组顺序(升序)
【发布时间】:2023-03-16 05:00:01
【问题描述】:

问题: 编写递归方法 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。

【问题讨论】:

  • 为您正在使用的编程语言添加标签。看起来可能是 C#,还是我猜错了? (是的,我猜错了,C# 不会有 boolean - 那么它是 Java 吗?)

标签: recursion


【解决方案1】:

我想我今天早上才弄明白。至少输出是我现在想要的。

代码:

    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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-12-03
    • 2020-08-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-12
    • 2021-03-27
    • 1970-01-01
    相关资源
    最近更新 更多