這是一個使用合併排序的程序 - 對從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代碼太多 – Bohemian