2013-01-08 64 views
0

这是一个使用合并排序的程序 - 对从1000到1000的1000个数字进行排序。 它显示原始列表,然后调用递归方法对其进行排序,然后显示它。调用方法内的方法?这在这种情况下如何工作? (Java)

我不代码中了解什么是这两行:

归并(数字,低,中); //在方法内,它会说“这里”

MergeSort(numbers,middle + 1,high);

我是java的初学者,这违背了我学习的一切,因为我无法理解如何调用方法中的方法。除非它是我怀疑的对象。 有人可以解释我这两行代码的作用吗?

import java.io.*; 
import java.util.*; 
import java.text.*; 

public class MergeSortExample 
{ 
    static final int Max = 1000; 

    static void MergeSort (int[] numbers, int lo, int n) // recursive method 
    { 

     int low = lo; // 0 
     int high = n; // 999 

     if (low >= high) // return case; 
     { 
      return; 
     } 

     int middle = (low + high)/2; 
     MergeSort (numbers, low, middle); // HERE 
     MergeSort (numbers, middle + 1, high); // HERE 

     int end_low = middle; 
     int start_high = middle + 1; 

     while ((lo <= end_low) && (start_high <= high)) 
     { 
      if (numbers [low] < numbers [start_high]) 
      { 
       low++; 
      } 
      else 
      { 
       int Temp = numbers [start_high]; 

       for (int k = start_high - 1 ; k >= low ; k--) 
       { 
        numbers [k + 1] = numbers [k]; 
       } 
       numbers [low] = Temp; 
       low++; 
       end_low++; 
       start_high++; 
      } 
     } 




    } 


    public static void main (String str[]) throws IOException 
    { 
     BufferedReader stdin = new BufferedReader (new InputStreamReader (System.in)); 
     DecimalFormat df = new DecimalFormat ("#"); 
     BufferedReader reader = new BufferedReader (new FileReader ("unsorted.txt")); 
     //BufferedWriter writer = new BufferedWriter (new FileWriter ("test.txt", true)); // text to write 


     int[] numbers = new int [Max]; // if its int the 0's in the beginiing would be cut off 
     String line = null; 
     int[] count = {0}; 

     int low = 0; 
     int high = count [0] - 1; 


     while ((line = reader.readLine()) != null) 
     { 
      numbers [count [0]] = Integer.parseInt (line); 
      System.out.println (numbers [count [0]]); 

      count [0]++; 
     } 
     reader.close(); 
     System.out.println(); 
     System.out.println ("There are " + count [0] + " numbers."); 
     System.out.println(); 


     /////////////////////////////////////////////////////////////////////////////// 


     MergeSort (numbers, 0, count [0] - 1); 

     for (int i = 0 ; i < count [0] ; i++) 
     { 
      System.out.println (numbers [i]); 
     } 




    } 
} 
+1

-1代码太多 – Bohemian

回答

0

当然,一个方法可能会调用另一种方法。这里唯一令人困惑的部分是这种方法是静态,这意味着它在而不是对象上被调用。由于它是在类中定义的,因此不需要编写MergeSortExample.MergeSort()。如果您想了解静态和实例方法和字段之间的差异,我建议您查看Java网站上的tutorials

1

这是基本的递归。合并排序的工作方式是将列表分成两部分,合并排序每一部分,然后将两个列表合并在一起。你所问的部分是合并的部分,将这两部分分别进行排序。

1

这是一个静态方法MergeSort()的递归调用。这里使用不好的约定。方法名称应以小写字母开头

相关问题