(1)算法基本功——快速排序
对文件 largeW.txt(下载链接)中的数据,应用快速排序算法进行排序,并与冒泡排序、归并排序进行时间比较。体验算法复杂度对设计算法的影响。
package javapage;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class QuickSort {
//读取文件数据
int[] readFile(){
int tempArray[] = new int[1000000],i=0;
Scanner myfile;
try {
myfile = new Scanner(new File("largeW.txt"));
while(myfile.hasNext()){//读取文件到数组
tempArray[i]=myfile.nextInt();
i++;
}
myfile.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return tempArray;
}
//快速排序
void QuickSort(int[] array,int start,int end){
if(start<end){
int key=array[start];//初始化保存基元
int i=start,j;//初始化i,j
for(j=start+1;j<=end;j++) {
if(array[j]<key)//如果此处元素小于基元,则把此元素和i+1处元素交换,并将i加1,如大于或等于基元则继续循环
{
int temp=array[j];
array[j]=array[i+1];
array[i+1]=temp;
i++;
}
}
array[start]=array[i];//交换i处元素和基元
array[i]=key;
QuickSort(array, start, i-1);//递归调用
QuickSort(array, i+1, end);
}
}
//冒泡排序
int[] bubbleSort(int[] bubbleArray){
int temp;
for(int i=bubbleArray.length-1;i>0;i--){//排序操作
for(int j=0;j<i;j++){
if(bubbleArray[j]>bubbleArray[j+1]){
temp=bubbleArray[j];
bubbleArray[j]=bubbleArray[j+1];
bubbleArray[j+1]=temp;
}
}
}
return bubbleArray;
}
//合并排序
int[] mergeSort(int[] arrays,int start,int end){//递归分成小部分
if(start<end){
int m=(start+end)/2;
mergeSort(arrays,start,m);
mergeSort(arrays,m+1,end);
return combin_arrays(arrays,start,m,end);
}
return new int[0];
}
int[] combin_arrays(int[] arrays,int start,int m,int end){//合并数组
int length=end-start+1;
int temp[]=new int[length];//用来存放比较的数组,用完复制回到原来的数组
int i=start;
int j=m+1;
int c=0;
while(i<=m &&j<=end){
if(arrays[i]<arrays[j]){
temp[c++]=arrays[i++];
}else{
temp[c++]=arrays[j++];
}
}
while(i<=m){
temp[c++]=arrays[i++];
}
while(j<=end){
temp[c++]=arrays[j++];
}
c=0;
for(int t=start;t<=end;t++,c++){
arrays[t]=temp[c];
}
return arrays;
}
void copyArr(int arr1[],int arr2[]){
for(int i=0; i<arr2.length;i++)
arr1[i] = arr2[i];
}
public static void main(String[] args){
QuickSort sort = new QuickSort();
int[] array=sort.readFile();
int[] arr = new int[array.length];
double starttime,endtime;
sort.copyArr(arr, array);
starttime = System.currentTimeMillis();
sort.QuickSort(arr, 0, arr.length-1); //快速排序
endtime = System.currentTimeMillis();
System.out.println("快速排序时间: " + (endtime-starttime) + "ms");
sort.copyArr(arr, array);
starttime = System.currentTimeMillis();
sort.mergeSort(arr,0,arr.length-1); //合并排序
endtime = System.currentTimeMillis();
System.out.println("合并排序时间: " + (endtime-starttime) + "ms");
sort.copyArr(arr, array);
starttime = System.currentTimeMillis();
sort.bubbleSort(arr); //冒泡排序
endtime = System.currentTimeMillis();
System.out.println("冒泡排序时间: " + (endtime-starttime) + "ms = " + (endtime-starttime)/1000 + "s");
}
}