1. 排序。对文件 largeW.txt(下载链接)中的数据,编程实现冒泡排序(方法名:bubbleSort) 与 归并排序(mergeSort),把排序后的结果分别保存到largeW_bubble.txt 和 largeW_merge.txt 中,把两种排序结果的运行时间输出到屏幕中(发博文时把运行时间的截图作为运行结果提交)。
注:由于源文件太大,进行冒泡排序时间较长,故取了一部分数据进行测试
package homework;
import java.io.*;
import java.util.*;
public class ch04{
public static void main(String[] args) throws IOException {
/*--------------------------------------冒泡排序-------------------------------------------*/
ArrayList<Integer> aList=getData();
Object [] dataSeqBubble=aList.toArray();
long bubbleBeginTime=System.currentTimeMillis();
Object [] infile=bubbleSort(dataSeqBubble);
long bubbleEndTime=System.currentTimeMillis();
System.out.println("冒泡排序---用时为:"+(bubbleEndTime-bubbleBeginTime)+"毫秒");
/*--------------------------------------归并排序-------------------------------------------*/
ArrayList<Integer> aList2=getData();
//将aList2转换为Object数组
Object [] dataSeqMerge=aList2.toArray();
int arraylength=dataSeqMerge.length;
Object [] newarray=new Object[arraylength];
long mergeBeginTime=System.currentTimeMillis();
mergeSort(dataSeqMerge, newarray, 0, arraylength-1);
long mergeEndTime=System.currentTimeMillis();
System.out.print("归并排序---用时为:"+(mergeEndTime-mergeBeginTime)+"毫秒");
}
//获取数据,返回一个ArrayList
public static ArrayList<Integer> getData() throws IOException{
FileReader fis=new FileReader("2e2.txt");
char[] readNum=new char[7];
int num=0;
ArrayList<Integer> al=new ArrayList<Integer>();
while ((num=fis.read(readNum))!=-1) {
String dataStoreString= new String(readNum,0,num).trim();
int dataStore=Integer.parseInt(dataStoreString);
al.add(dataStore);
}
fis.close();
return al;
}
//冒泡排序
public static Object[] bubbleSort(Object [] dataArrayList) {
int temp=0;
for (int i = 0; i < dataArrayList.length-1; i++) {
for (int j = 0; j < dataArrayList.length-1-i; j++) {
if ((Integer)dataArrayList[j]>(Integer)dataArrayList[j+1]) {
temp=(Integer)dataArrayList[j];
dataArrayList[j]=dataArrayList[j+1];
dataArrayList[j+1]=temp;
}
}
}
return dataArrayList;
}
//一次归并算法
public static void merge(int first,int mid,int last,Object firstArray[],Object finalArray[]){
int i=first;
int j=mid+1;
//最终数组开始位置
int k=first;
while(i<=mid && j<=last){
if ((Integer)firstArray[i] <= (Integer)firstArray[j]) {
finalArray[k++]=firstArray[i++];
}
else {
finalArray[k++]=firstArray[j++];
}
}
if (i<=mid) {
while (i<=mid) {
finalArray[k++]=firstArray[i++];
}
}
else{
while (j<=last) {
finalArray[k++]=firstArray[j++];
}
}
}
//归并排序
public static void mergeSort(Object firstArray[],Object finalArray[],int first,int last){
if(first==last) //待排序只有一个记录,递归结束
finalArray[first]=firstArray[first];
else {
int mid=(first+last)/2;
mergeSort(firstArray, finalArray, first, mid);//对数组前半段进行排序
mergeSort(firstArray, finalArray, mid+1, last);//对数组前半段进行排序
merge(first, mid, last, finalArray, firstArray);//合并
}
}
}