对文件 largeW.txt(下载链接)中的数据,应用快速排序算法进行排序,并与冒泡排序、归并排序进行时间比较。体验算法复杂度对设计算法的影响。
比较算法:冒泡排序、归并排序(之前博客已测试)
类说明:
1.ReadFile - 读取文件数据
2.WriteFile - 数据写入文件
3.QuickSort - 快速排序实现
4.Main - 测试类
代码如下:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ReadFile
{
public int[] readArray(String filePath) throws FileNotFoundException
{
int count = 0;
Scanner scan = new Scanner(new File(filePath));
while (scan.hasNextInt())
{
count++;
scan.nextInt();
}
int[] array = new int[count];
scan = new Scanner(new File(filePath));
int index = 0;
while (scan.hasNextInt())
{
array[index] = scan.nextInt();
index++;
}
scan.close();
return array;
}
}
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
public class WriteFile
{
public void writeToFile(int[] array, String fileName)
throws FileNotFoundException
{
PrintWriter pw = new PrintWriter(new File(fileName));
for (int i = 0, lineCount = array.length; i < lineCount; i++)
{
pw.println(array[i]);
}
pw.close();
}
}
public class QuickSort
{
public int once(int[] array, int start, int end)
{
int i = start, j = end, temp = 0;
while (i < j)
{
while (i < j && array[i] <= array[j])
j--;
if (i < j)
{
temp = array[i];
array[i] = array[j];
array[j] = temp;
i++;
}
while (i < j && array[i] <= array[j])
i++;
if (i < j)
{
temp = array[i];
array[i] = array[j];
array[j] = temp;
j--;
}
}
return i;// 返回记录的位置
}
public void quickSort(int[] array, int start, int end)
{
if (start < end)
{
int location = once(array, start, end);
quickSort(array, start, location - 1);
quickSort(array, location + 1, end);
}
}
}
import java.io.FileNotFoundException;
import QuickSort;
import ReadFile;
import WriteFile;
public class Main
{
public static void main(String[] args)
{
ReadFile rf = new ReadFile();
try
{
int[] array = rf.readArray("largeW.txt");
QuickSort qs = new QuickSort();
long startTime = System.currentTimeMillis();
qs.quickSort(array, 0, array.length - 1);
long endTime = System.currentTimeMillis();
System.out.println("快速排序使用时长:" + (endTime - startTime) + "ms");
WriteFile wf = new WriteFile();
wf.writeToFile(array, "txt/sorted.txt");
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
}
运行时间:163ms