冒泡排序代码:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;
public class ReadData {
public static void main(String[] args) throws FileNotFoundException{
ReadData b=new ReadData();
long start = System.currentTimeMillis();
Scanner sc = new Scanner(new File("largeW.txt"));
PrintWriter pw = new PrintWriter(new File("largeW_bubble.txt"));
long a[]=new long[1000000];
long i=0;
while(sc.hasNextInt()&&i<a.length){
a[(int)i++]= sc.nextInt();
}
b.bubbleSort(a,a.length);
for(i=0;i<a.length;i++){
pw.printf("%d: %d\n", i+1,a[(int)i]);
}
pw.close();
sc.close();
System.out.println("运行结束,一共有"+a.length+"个数据。");
long end = System.currentTimeMillis();
long t=end-start;
System.out.println("程序运行时间:"+t/1000+"秒");
}
public void bubbleSort(long a[],long n){
long m=n;
for(long i=m-1;i>0;i--)
for(long j=0;j<=i-1;j++)
if(a[(int)j]>a[(int)j+1]){
long t=a[(int)j+1];
a[(int)j+1]=a[(int)j];
a[(int)j]=t;
}
}
}
运行结果:
归并排序代码:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;
public class ReadData1 {
public static void main(String[] args) throws FileNotFoundException{
ReadData1 b=new ReadData1();
Scanner sc = new Scanner(new File("largeW.txt"));
PrintWriter pw = new PrintWriter(new File("largeW_merge.txt"));
long r[]=new long[1000000];
long i=0;
while(sc.hasNextInt()&&i<r.length){
r[(int)i++]= sc.nextInt();
}
long r1[]=new long[1000000];
long start = System.currentTimeMillis();
b.MergeSort(r, r1, r.length);
long end = System.currentTimeMillis();
for(i=0;i<r.length;i++){
pw.printf("%d: %d\n", i+1,r[(int)i]);
}
pw.close();
sc.close();
System.out.println("运行结束,一共有"+r.length+"个数据。");
long t=end-start;
System.out.println("程序运行时间:"+t+"毫秒");
}
void Merge(long r[],long r1[],long s,long m,long t){
long i=s,j=m+1,k=s;
while(i<=m&&j<=t){
if(r[(int)i]<=r[(int)j])
r1[(int)k++]=r[(int)i++];
else
r1[(int)k++]=r[(int)j++];
}
if(i<=m)
while(i<=m)
r1[(int)k++]=r[(int)i++];
else
while(j<=t)
r1[(int)k++]=r[(int)j++];
}
void MergePass(long r[],long r1[],long n,long h){
long i=0;
while(i<=n-2*h){
Merge(r,r1,i,i+h-1,i+2*h-1);
i+=2*h;
}
if(i<n-h)
Merge(r,r1,i,i+h-1,n-1);
else
for(long k=i;k<n;k++)
r1[(int)k]=r[(int)k];
}
void MergeSort(long r[],long r1[],long n){
long h=1;
while(h<n){
MergePass(r,r1,n,h);
h=2*h;
MergePass(r1,r,n,h);
h=2*h;
}
}
}
运行结果: