簡體   English   中英

java mergesort計數作業

[英]java mergesort count homework

我正在努力在合並排序時獲取比較和移動器的計數。 我想我要歸功於此排序比較計數器,但我無法將其打印出來。 我顯然是編程新手,所以如果您能解釋我所缺少的內容,我將不勝感激。

import java.util.Arrays;


public class MergeSort {
int count = 0;
/**
 * @param args
 */

// Rearranges the elements of a into sorted order using
// the merge sort algorithm (recursive).
public int mergeSort(int[] a, int howMany) {


    if (a.length >= 2) {
        // split array into two halves
        int[] left  = Arrays.copyOfRange(a, 0, a.length/2);
        int[] right = Arrays.copyOfRange(a, a.length/2, a.length);


        // sort the two halves
       howMany = mergeSort(left,howMany);
       howMany = mergeSort(right, howMany);

        // merge the sorted halves into a sorted whole
       howMany = merge ( left, right, a, howMany);


    }

   return howMany;
}




// Merges the left/right elements into a sorted result.
// Precondition: left/right are sorted
public static int merge(int[] result, int[] left, 
                                       int[] right, int howMany) {
    int i1 = 0;   // index into left array
    int i2 = 0;   // index into right array

    for (int i = 0; i < result.length; i++) {
        if (i2 >= right.length ||
           (i1 < left.length && left[i1] <= right[i2])) {
            result[i] = left[i1];    // take from left
            i1++;
        } else {
            result[i] = right[i2];   // take from right
            i2++;
        }

    }

    return howMany;
}

System.out.println(howMany); // ???
}

您需要在要打印的任何地方通過其對象調用該方法。 這樣的事情(可能在您的main方法中):

MergeSort mObj - new MergeSort();
int[] array = {1,2,3};
int count =  mObj.mergeSort(array, 2);
System.out.println(count);

基本上,您需要一個驅動程序方法。 運行Java類時,它將尋找一個public static void main(String[] args)方法; 如果不存在此方法,則不會發生任何事情。 現在,您實際上應該從System.out.println(howMany);獲得編譯錯誤System.out.println(howMany); 因為變量howMany僅存在於merge方法的范圍(括號)內。 為了更好地理解這一點,我將回顧您關於變量和方法范圍以及類成員的注釋。 為了快速解決,請刪除我上面提到的底部的行,然后將此方法放在類中的某個位置:

public static void main(String[] args) {
    int[] array = {2,5,8,1,3};
    int howMany = mergeSort(array, 5);
    System.out.println(howMany);
}

您還需要使mergeSort方法為static方法,因此將其定義更改為

public **static** int mergeSort(int[] a, int howMany)

我測試了您的代碼,我很確定它沒有給出您想要的答案,因此請務必進行檢查。 最好的運氣學習面向對象編程!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM