2016-01-04 20 views
1

我想在數組中找到一個「峯值」(a1 ai + 1> ...> an的值,這裏ai是峯值)。我在這裏使用分治法來獲得更優化的解決方案。對於「6 1 3 50 70 100 48」,它會打印出好的「70 100 48 4」(70 < 100和100> 48),但它不返回Integer.toString(a [m]),它返回「陣列沒有高峯「。我試圖刪除字符串和int工作,但我得到完全相同的問題。程序不返回

public class Main { 

    public int n, a[]; 

    void read() { 
     File file = new File("src/com/fmi/Vector.txt"); 
     Scanner sc; 

     try { 
      sc = new Scanner(file); 
      int i = 0; 
      if (sc.hasNextInt()) { 
       n = sc.nextInt(); 
      } 
      a = new int[n]; 
      while (sc.hasNextInt()) { 
       int aux = sc.nextInt(); 
       a[i] = aux; 
       i++; 
      } 
     } catch (FileNotFoundException e) { 
      System.out.println("File not found!"); 
     } 
    } 

    String search(int p, int u) { 
     int m; 
     System.out.println(p + " " + u); 
     if (p == u) { 
      return "0"; 
     } else { 
      m = (p + u)/2; 
      System.out.println(a[m - 1] + " " + a[m] + " " + a[m + 1] + " " + m); 
      if (a[m - 1] < a[m] && a[m] > a[m + 1]) { 
       return Integer.toString(a[m]); 
      } else if (a[m - 1] < a[m] && a[m] < a[m + 1]) { 
       search(m, u); 
      } else if (a[m - 1] > a[m] && a[m] > a[m + 1]) { 
       search(p, m); 
      } 
     } 
     return "Array has no peak!"; 
    } 

    void display() { 
     for (int i = 0; i < n; i++) { 
      System.out.print(a[i] + " "); 
     } 
     System.out.println(" "); 
     for (int i = 0; i < n; i++) { 
      System.out.print(i + " "); 
     } 
    } 

    public static void main(String[] args) { 
     Main obj = new Main(); 
     obj.read(); 
     System.out.println(obj.search(0, obj.n)); 
     obj.display(); 
    } 
} 
+0

請格式化你的代碼。可怕的閱讀。 –

+0

刪除文件讀取並直接在代碼中添加值。這既能確保問題不在文件讀取中,又能讓我們重現錯誤。 – Keppil

+0

並嘗試簡化這些條件。你有沒有調試和檢查實際的調用搜索和你的條件測試的價值? – Stultuske

回答

2

你打電話給搜索,但你沒有做任何結果。 你應該做點像

return search(m,u); 
+0

哦,我錯過了。謝謝! –