这是工作合并排序方法。问题是我想在屏幕上打印排序的步骤,并在单独的文本文件上打印最终的排序结果。由于它是递归的,它比上面需要的几倍。编辑:如何只在文本文件上写一次最终数组?
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class Merge
{
public static void Sort (LinkedList listIn, int size) throws Exception
{
String[] mArray = new String[size] ;
String textContent = null ;
File outputFile ;
do
{
outputFile = new File("[Merge] Sorted Entries.txt") ;
if(!outputFile.exists())
{
outputFile.createNewFile ();
System.out.println("Sorted file created.txt");
System.out.println("");
}
else
{
System.out.println("File Updated.");
}
}while (!outputFile.exists()) ;
//copy the list values in the array
for (int i = 0 ; i < size ; i++)
{
mArray [i] = listIn.get(i).printNode();
}
mergeSort(mArray, 0, mArray.length-1) ;
}
public static <T extends Comparable<? super T>> void mergeSort(T[] array, int min, int max) throws Exception
{
T[] temp ;
int index1 ;
int left ;
int right ;
Stopwatch timer = new Stopwatch().start();
// if array is of size 1
if (min == max)
return ;
// find length and midpoint
int size = max - min + 1 ;
int pivot = (min + max) / 2 ;
temp = (T[]) (new Comparable[size]) ;
mergeSort(array, min, pivot) ;
mergeSort(array, pivot + 1, max) ;
for (index1 = 0 ; index1 < size ; index1++)
{
temp[index1] = array[min + index1] ;
}
left = 0 ;
right = pivot - min + 1 ;
for (index1 = 0 ; index1 < size ; index1++)
{
if (right <= max - min)
if (left <= pivot - min)
if (temp[left].compareTo(temp[right]) > 0)
array[index1 + min] = temp[right++] ;
else
array[index1 + min] = temp[left++] ;
else
array[index1 + min] = temp[right++] ;
else
array[index1 + min] = temp[left++] ;
}
timer.stop() ;
}
public static <T extends Comparable<? super T>> void output (T[] array, int index)
{
System.out.println(array[index] + " ") ;
}
}