我冒个泡,然后开始排序!
读入文件和排序后写出文件的冒泡排序。异常处理全都是throws
冒泡排序:
package exercise3;
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.List;
public class bubbleSort {
private static BufferedReader bufferedreader;
public static void main(String[] args) throws IOException{
bufferedreader = new BufferedReader(new InputStreamReader(new FileInputStream(new File("自定义")), "gb2312"));
String getData="";
int num=0;
List<Integer> list=new ArrayList<Integer>();
while((getData=bufferedreader.readLine())!=null){
num=num+1;
list.add(Integer.parseInt(getData.trim()));
}
Integer[] dataArray=(Integer[])list.toArray(new Integer[num]);
long timeStart=System.currentTimeMillis();
bubbleSort(dataArray);
long timeEnd=System.currentTimeMillis();
write(dataArray);
System.out.println("largeW.txt文本中总共有:"+num+"个数据\n"+"该数据冒泡排序所花费的时间是:\n"+(timeEnd-timeStart)+"毫秒");
}
private static void bubbleSort(Integer[] dataArray) throws IOException{
Integer[] arr=(Integer[]) dataArray;
for(int i=0;i<arr.length;i++){
for(int j=i+1;j<arr.length;j++){
if(arr[i]>arr[j]){
int temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
}
}
}
public static void write(Integer[] arr) throws IOException{
System.out.println("排序后的文件已经创建,保存在:\n自定义");
File file =new File("自定义");
if(!file.exists()){
file.createNewFile();
}
FileOutputStream fos=new FileOutputStream(file);
BufferedWriter writer=new BufferedWriter(new OutputStreamWriter(fos,"gb2312"));
for(int i=0;i<arr.length;i++){
writer.write(arr[i].toString()+"\r\n");
writer.flush();
}
fos.close();
writer.close();
}
}
记事本写入的数据如下:
请点击归并排序,那里有详细介绍,有各种语言编写的。只需要把它覆盖以上的冒泡排序的排序部分就可以了。