您的位置:首页 > 其它

第三周作业-冒泡排序与归并排序

2014-03-28 11:20 381 查看
package test;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class  sortnum{
static String path="C:/Users/玲/Desktop/largeW.txt";
static String bubbleSortpath="C:/Users/玲/Desktop/bubbleNum.txt";	//冒泡排序结果存放位置
static String mergeSortpath="C:/Users/玲/Desktop/mergeNum.txt";		//归并排序结果存放位置
public static void main(String[] args) {
try {
File file=new File(path);
FileInputStream fin=new FileInputStream(file);
InputStreamReader inread=new InputStreamReader(fin, "gb2312");
BufferedReader buffread=new BufferedReader(inread);
String nums="";
int num=0;
List list=new ArrayList();
while((nums=buffread.readLine())!=null){
num=num+1;
list.add(Integer.parseInt(nums.trim()));
}
Integer[] numArray=(Integer[])list.toArray(new Integer[num]);
long timeStart=System.currentTimeMillis();	//开始冒泡排序计时
bubbleSort(numArray);
long timeEnd=System.currentTimeMillis();	//冒泡排序计时结束
System.out.println("冒泡排序所花费的时间是:"+(timeEnd-timeStart)+"毫秒");
ResultSortWriteTxt(numArray,0);//冒泡排序结果写到文本文件

numArray=(Integer[])list.toArray(new Integer[num]);
Integer[] num0=new Integer[numArray.length];
timeStart=System.currentTimeMillis();//开始归并排序计时
Integer[] result  = mergeSort(numArray, 0, numArray.length - 1, num0);
timeEnd=System.currentTimeMillis();//归并排序计时结束
System.out.println("归并排序所花费的时间是:"+(timeEnd-timeStart)+"毫秒");
ResultSortWriteTxt(result,1);//把归并排序的结果写到文本文件
System.out.println("文本中总共有:"+num+"条数据");
} catch (Exception e) {
e.printStackTrace();
}
}

public static void bubbleSort(Integer[] Array) throws IOException{//冒泡排序
Integer[] numArray=(Integer[]) Array;
int k=0;
for(int i=0;inumArray[j]){
k=numArray[i];
numArray[i]=numArray[j];
numArray[j]=k;
}
}

}
}

public static void  ResultSortWriteTxt(Integer[] numArray,int whichSort) throws IOException{
File file=null;
if(whichSort==0){					//冒泡排序是表示0
file =new File(bubbleSortpath);
}else if(whichSort==1){			//归并排序是表示1
file =new File(mergeSortpath);
}
if(!file.exists()){
file.createNewFile();
}
FileOutputStream fout=new FileOutputStream(file);
BufferedWriter buffwrite=new BufferedWriter(new OutputStreamWriter(fout,"gb2312"));
for(int i=0;i
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: