package d;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;
public class sort {
public static void main(String[] args) {
readFile rf = new readFile();
bubbleSort bs = new bubbleSort();
writFile wf = new writFile();
mergeSort ms = new mergeSort();
double starttime1 = System.currentTimeMillis();//开始时间
wf.writFile(bs.bubbleSort(rf.readFile()),"largeW_bubble.txt");//选择排序的运行
double endtime1 = System.currentTimeMillis();//结束时间
System.out.println("bubble sort time: " + (endtime1-starttime1) + "ms");//显示排序时间
double starttime2 = System.currentTimeMillis();//开始时间
wf.writFile(ms.mergeSort(rf.readFile(), 0, rf.readFile().length-1),"largeW_merge.txt");
double endtime2 = System.currentTimeMillis();//结束时间
System.out.println("merge sort time: " + (endtime2-starttime2) + "ms");//显示排序时间
}
}
/
class writFile {//写入文件
public void writFile(int[] wArray,String srcfile){
int num = 0;
PrintWriter pw;
try {
pw = new PrintWriter(new File(srcfile));
while(wArray.length>num){//写数组到文件
pw.printf("%d: %d\n", num+1,wArray[num]);//写入文件格式
num++;
}
pw.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
System.out.println("运行结束,一共有"+num+"个数据。");
}
}
/
class readFile{//读取文件
public 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;
}
}
///
class bubbleSort{//冒泡排序
public int[] bubbleSort(int[] bubbleArray){
int temp;
//double start = System.currentTimeMillis();//开始时间
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;
}
}
}
//double end = System.currentTimeMillis();//结束时间
//System.out.println("time: " + (end-start) + "ms");//显示排序时间
return bubbleArray;
}
}
//
class mergeSort{//合并排序
public 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];
}
public 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;
}
}