import java.io.*;
import java.util.ArrayList;
import java.util.List;
public class sort {
public static void main(String[] args)
{
List<Integer> dataList = getdata();
long beginTime = System.currentTimeMillis();
bubbleSort(dataList);
long stopTime = System.currentTimeMillis();
System.out.println("冒泡排序总用时:" + (stopTime - beginTime));
outtotxt(dataList.toArray());
}
//读取文件
private static List<Integer> getdata() {
List<Integer> data=new ArrayList<Integer>();
try{
FileReader fr=new FileReader("src/largeW.txt");
BufferedReader br=new BufferedReader(fr);
String line=br.readLine();
while(line!=null)
{
data.add(Integer.parseInt(line.trim()));
line=br.readLine();
}
}
catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return data;
}
//冒泡排序
public static long bubbleSort(List<Integer> datalist)
{long beginTime = System.currentTimeMillis();
int n=datalist.size();
for(int i=0;i<n-1;i++)
{
for(int j=0;j<n-i-1;j++)
{
if(datalist.get(i)<datalist.get(j))
{
int tempdata=datalist.get(i);
datalist.set(j,datalist.get(j+1));
datalist.set(j+1, tempdata);
System.out.println(datalist.get(j));
}
}
}
long endTime = System.currentTimeMillis();
return endTime-beginTime;
}
//输出到文件
public static void outtotxt(Object[] datalist)
{
FileWriter outdata=null;
try {
File outtxt=new File("src/largeW_bubble.txt");
outdata=new FileWriter(outtxt);
for (int i=0; i<datalist.length; i++) {
Integer integer = (Integer)datalist[i];
//System.out.println(integer);
outdata.write(integer + "\n");
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
outdata.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}//class
第三周作业——冒泡排序和归并排序(只完成冒泡算法)
最新推荐文章于 2024-07-30 20:48:34 发布