2013-04-13 101 views
-1

在下面的代碼中,merge()函數只被調用了兩次,然後進入了一些無限循環。這個合併排序實現有什麼問題

package Prac; 


public class MergeSort { 

    private static int[] arr = {12, 10, 5, 2, 7, 56, 81, 17, 14, 1 }; 
    private static int[] helper; 

    public static void main(String[] args) { 

     MergeSort ob = new MergeSort(); 
     ob.sort(); 
     for (int i : arr) { 
      System.out.println(arr[i]); 
     } 
    } 

    private void sort() { 
     int number = arr.length; 
     helper = new int[number]; 
     mergeSort(0, number - 1); 
    } 

    private void mergeSort(int low, int high) { 
     if (low < high) { 
      int middle = (low + (high - low))/2; 
      mergeSort(low, middle); 
      mergeSort(middle + 1, high); 
      merge(low, middle, high); 
     } 
    } 

    private void merge(int low, int middle, int high) { 
     for (int i = low; i <= high; i++) { 
      helper[i] = arr[i]; 
     } 
     int firstPointer = low; 
     int secondPointer = middle + 1; 
     int insertPointer = low; 
     while (firstPointer <= middle && secondPointer <= high) { 
      if (helper[firstPointer] < helper[secondPointer]) { 
       arr[insertPointer] = helper[firstPointer]; 
       firstPointer++; 
      } else { 
       arr[insertPointer] = helper[secondPointer]; 
       secondPointer++; 
      } 
      insertPointer++; 
     } 
     if (firstPointer < middle || middle == 0) { 
      while (firstPointer <= middle) { 
       arr[insertPointer] = helper[firstPointer]; 
       firstPointer++; 
       insertPointer++; 
      } 
     } else { 
      while (secondPointer <= high) { 
       arr[insertPointer] = helper[secondPointer]; 
       secondPointer++; 
       insertPointer++; 
      } 
     } 
    } 
} 
+5

步驟通過與調試你的代碼。 –

回答

2

我認爲你的問題是在這裏

int middle = (low + (high - low))/2; ??????????????????? 

需要注意的是:(low + (high - low))/2等於hight/2

所以正確的中間功能離子是:

int middle = (low + high)/2;


2

要獲得的中間位置應該是:

int middle = low + ((high - low)/2);