對文件 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();
}
}
}
運行結果: