对文件 largeW.txt(下载链接)中的数据,应用快速排序算法进行排序,并与冒泡排序、归并排序进行时间比较。体验算法复杂度对设计算法的影响。
比较算法:冒泡排序、归并排序(之前博客已测试)
类说明:
1.ReadFile - 读取文件数据
2.WriteFile - 数据写入文件
3.QuickSort - 快速排序实现
4.Main - 测试类
代码实现:
package com.here.tools;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
/**
* @date 2014-6-12
* @info 读取文件数据
*/
public class ReadFile {
/**
*
* @param filePath 文件路径
* @return 整型数组
* @throws FileNotFoundException
*/
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;
}
}
package com.here.tools;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
/**
* @date 2014-6-12
* @info 数据写入文件
*/
public class WriteFile {
/**
*
* @param array 待写入数据
* @throws FileNotFoundException
*/
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();
}
}
package com.here.tools;
/**
* @date 2014-6-12
* @info
*/
public class QuickSort {
/**
* 第一次划分大小
* @param array 需要排序的数组
* @param start 数组的第一个元素array[0]
* @param end 数组的最后一个元素array[end-1]
* @return 扫描完毕指针的位置
*/
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;//返回记录的位置
}
/**
*
* @param array 待排序数组
* @param start 数组第一个元素array[0]
* @param end 数组最后一个元素array[end-1]
*/
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);
}
}
}
package com.here.test;
import java.io.FileNotFoundException;
import com.here.tools.QuickSort;
import com.here.tools.ReadFile;
import com.here.tools.WriteFile;
public class Main {
public static void main(String[] args) {
ReadFile rf = new ReadFile();
try {
//读取文件数据
int[] array = rf.readArray("txt/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();
}
}
}
运行结果: