递归MergeSort和计数比较

时间:2010-10-01 19:23:20

标签: java

我编写了一个包含4种排序方法,选择排序,插入排序,合并排序和递归合并排序的程序。插入和选择排序方法运行正常,并返回一个排序列表和正确的比较量。我的合并排序方法返回一个排序列表,但我的比较= 1.我的递归合并排序甚至不排序列表,并说比较= 1.任何人都可以帮我找到我的错误?这是我的所有代码。

public class ArraySort {
    private long[] a;                 // ref to array a
    private int nElems;               // number of data items

    public ArraySort(int max) {       // constructor
       a = new long[max];             // create the array
       nElems = 0;                    // no items yet
    }

    public void Clone(ArraySort c) {  // c is another array
       c.nElems = this.nElems;                                 // Copy nElems
       System.arraycopy(this.a, 0, c.a, 0, this.nElems);       // Copy elements
    }

    public void insert(long value) {  // put element into array
       a[nElems++] = value;           // insert value
    }

    public String toString() {           // displays array contents
       String res="";
       for(int j=0; j<nElems; j++)       // for each element,
          res = res + a[j] + " ";        // append it to res
       return res;
    }

    private int insertOrder(int n, long temp) { // insert temp into a[0..(n-1)]
                  // and keep a[0..n] sorted.
        int count = 0;
        while (n > 0) {
            count++;                       // count next comparison
            if (a[n-1] > temp)   {         // until one is smaller,
               a[n] = a[n-1];              // shift item to right
               --n;                        // go left one position
            } else break;
        }
        a[n] = temp;                      // insert marked item
        return count;
    }

    public int insertionSort() {
        int count = 0;
        for (int n=1; n<nElems; n++)  
            count += insertOrder(n, a[n]);   // insert a[n] into a[0..(n-1)]

        return count;
    } // end insertionSort()

    private void swap(int one, int two) {
       long temp = a[one];
       a[one] = a[two];
       a[two] = temp;
    }

    public int selectionSort() {
       int out, in, max, count=0;

       for(out=nElems-1; out > 0; out--) {  // outer loop
          max = out;                        // max is maximum item's index
          for(in=0; in<out; in++) {          // inner loop
             if(a[in] > a[max] )            // if max is smaller,
                 max = in;                  // we have a new max
             count++;                       // count one comparison
          }
          swap(out, max);                   // swap them
       }  // end for(out)
       return count;
    }  // end selectionSort()

    public int mergeSort() {           // called by main()
        int count = 0;
        long[] workSpace = new long[nElems]; // provides workspace
        recMergeSort(workSpace, 0, nElems-1);
        count++;
        return count;
    }


public int recMergeSort(long[] workSpace, int lowerBound,
        int upperBound) {

    int count = 0;

    if(lowerBound == upperBound)            // if range is 1,
        return 1;

    // find midpoint
    int mid = (lowerBound+upperBound) / 2;

    recMergeSort(workSpace, lowerBound, mid);   // sort low half

    recMergeSort(workSpace, mid+1, upperBound);  // sort high half


    merge(workSpace, lowerBound, mid+1, upperBound); // merge them
    count++;
    return count;

}  // end else
  // end recMergeSort()


private int merge(long[] workSpace, int lowPtr,
        int highPtr, int upperBound)
{
    int j = 0;                             // workspace index

    int lowerBound = lowPtr;

    int mid = highPtr-1;

    int n = upperBound-lowerBound+1;       // # of items

    int count = 0;

    while(lowPtr <= mid && highPtr <= upperBound)

        if( a[lowPtr] < a[highPtr] ) {
            workSpace[j++] = a[lowPtr++];
            count++;
        }

        else {
            workSpace[j++] = a[highPtr++];
            count++;
        }

        while(lowPtr <= mid)
            workSpace[j++] = a[lowPtr++];

        count++;


        while(highPtr <= upperBound)
            workSpace[j++] = a[highPtr++];

        count++;

        for(j=0; j<n; j++)

           a[lowerBound+j] = workSpace[j];

        return count;
    }  // end merge()
}

从这里开始调用这些方法......

import java.util.*;

public class SortComparison {

    public static void main(String[] args) {

       int count, maxSize = 20;      // array size
       ArraySort arr, carr;           // reference to array
       arr = new ArraySort(maxSize);  // create the arrays
       carr = new ArraySort(maxSize);

       // insert some random numbers
              Random generator = new Random();
       for (int i = 0; i < 20; i++) {
            arr.insert(Math.abs(generator.nextInt())%maxSize);
       }

       System.out.println("Before sort: " + arr);                // display items

       arr.Clone(carr);
       count = carr.insertionSort();          // insertion-sort a clone of arr
       System.out.println("Insert sort: " + carr + " comparions=" + count);                  

       arr.Clone(carr);
       count = carr.selectionSort();          // selection-sort a clone of arr
       System.out.println("Select sort: " + carr + " comparions=" + count); 

       arr.Clone(carr);
       count = carr.mergeSort();
       System.out.println("Merge sort: " + carr + " comparions=" + count);

       arr.Clone(carr);
       count = carr.recMergeSort(null, maxSize, maxSize);
       System.out.println("RecMerge sort: " + carr + " comparions=" + count);

  }  // end main()

}  // end class SortComparison

当程序运行时,这是我收到的输出......

Before sort: 3 2 4 7 17 11 3 0 14 6 8 7 12 15 0 0 9 4 7 16 
Insert sort: 0 0 0 2 3 3 4 4 6 7 7 7 8 9 11 12 14 15 16 17  comparions=94
Select sort: 0 0 0 2 3 3 4 4 6 7 7 7 8 9 11 12 14 15 16 17  comparions=190
Merge sort: 0 0 0 2 3 3 4 4 6 7 7 7 8 9 11 12 14 15 16 17  comparions=1
RecMerge sort: 3 2 4 7 17 11 3 0 14 6 8 7 12 15 0 0 9 4 7 16  comparions=1

有人可以帮我解决这个问题吗?


我不知道为什么我的递归合并排序方法不会对列表进行排序。为什么比较=最后两个为1。

3 个答案:

答案 0 :(得分:2)

由于这是一项功课,我只会说明如何修复mergeSort()

public int mergeSort() {
    int count = 0;
    long[] workSpace = new long[nElems];
    count += recMergeSort(workSpace, 0, nElems-1); // Add the comparisons executed there
    return count;
}

您需要以类似的方式修复recMergeSort()

我想你认为count是一个全局变量。但事实并非如此。在所有排序方法中,count是一个局部变量,在方法范围之外是不可见的。因此,如果您修改count中的recMergeSort()变量,则不会自动影响count中的(其他)mergeSort()变量。将(从)recMergeSort()“发送”到(调用)mergeSort()的计数的自然方式是return count,正如您所做的那样。不幸的是,您没有使用recMergeSort()返回的结果。

最后一件事,因为我可能不够清楚:即使你从recMergeSort()递归调用recMergeSort(),调用者中的count变量仍然与{{count不同被调用者中的1}}变量。因此,即使你进行递归调用,被调用的方法仍然需要通过return传递结果,并且调用方法需要将其提取。

答案 1 :(得分:1)

以下是您的mergeSort()方法:

public int mergeSort() {           // called by main()
    int count = 0;
    long[] workSpace = new long[nElems]; // provides workspace
    recMergeSort(workSpace, 0, nElems-1);
    count++;
    return count;
}

此方法返回1,因为您创建了一个名为count的变量,在调用recMergeSort后将其一次递增一次,然后返回它。 recMergeSort包含另一个名为count的局部变量,但此局部变量mergeSort中的完全分开count++中的recMergeSort行对count内的mergeSort没有影响。

您的mergerecMergeSort方法都会返回所做的比较次数,但您不会对返回的值执行任何操作。要计算比较总数,请删除上面的count++行,并替换行

recMergeSort(workSpace, 0, nElems-1);

count += recMergeSort(workSpace, 0, nElems-1);

您还需要对recMergeSort中的各种方法调用进行类似的更改。

为什么上面输出的最后一行没有排序列表?好吧,您正在进行以下方法调用:

count = carr.recMergeSort(null, maxSize, maxSize);

您的recMergeSort方法开头如下:

public int recMergeSort(long[] workSpace, int lowerBound,
        int upperBound) {

    int count = 0;

    if(lowerBound == upperBound)            // if range is 1,
        return 1;

    // rest of method omitted
}

您明确呼叫recMergeSortlowerBoundupperBound参数相同。因此,该方法返回1,因为您明确要求它。

答案 2 :(得分:0)

将来,只需发布​​相关代码即可。我们不一定需要看到所有有用的方法。

有可能只使用一种方法制作递归排序算法(就个人而言,我认为如果你这样做会更容易)。无论如何,你在非常正确的轨道上。但是看看mergeSort() - 你声明count = 0,做你的递归,加1来计数,然后返回它。你遇到的问题是你只需要递增一次count,当你应该给它recMergeSort()返回的值。有关解决方案,请参阅我的在线评论。

public int mergeSort() {           // called by main() 
    int count = 0;

    long[] workSpace = new long[nElems]; // provides workspace
        /*
           recMergeSort() returns an integer, but you do not assign it to anything.
        */
    recMergeSort(workSpace, 0, nElems-1);
    count++;
        /* Instead, try something like 
               count = recMergeSort(workspace, 0, nElms-1);
               return count;
        */
return count;
}


public int recMergeSort(long[] workSpace, int lowerBound, int upperBound) { int count = 0;
    if(lowerBound == upperBound) // if range is 1, return 1;
    // find midpoint int mid = (lowerBound+upperBound) / 2;
    recMergeSort(workSpace, lowerBound, mid); // sort low half
    recMergeSort(workSpace, mid+1, upperBound); // sort high half
    merge(workSpace, lowerBound, mid+1, upperBound); // merge them count++; return count; } // end else // end recMergeSort()
    private int merge(long[] workSpace, int lowPtr, int highPtr, int upperBound) { int j = 0; // workspace index
    int lowerBound = lowPtr;
    int mid = highPtr-1;
    int n = upperBound-lowerBound+1; // # of items
    int count = 0;
    while(lowPtr <= mid && highPtr <= upperBound)
    if( a[lowPtr] < a[highPtr] ) {
        workSpace[j++] = a[lowPtr++];
        count++;
    } else {
        workSpace[j++] = a[highPtr++];
        count++; }
    while(lowPtr <= mid)
        workSpace[j++] = a[lowPtr++];
        count++;
    while(highPtr <= upperBound)
        workSpace[j++] = a[highPtr++];
        count++;
    for(j=0; j


                       //AAAAAH! What happened to your For loop???

        a[lowerBound+j] = workSpace[j]; return count; } // end merge()

}