public class And extends Thread{
private int[] A;
private int first;
private int end;
public And(int[] A,int first,int end){
super();
this.A=A;
this.first=first;
this.end=end;
}
public void run(){
quickSort(A,first,end);
}
public void quickSort(int[] A, int first, int end)
{
int i = first, j = end;
int tmp;
if (first < end)
{
tmp = A[first];
while (i != j)
{
while (j > i && A[j] >= tmp)
j--;
A[i] = A[j];
while (i < j && A[i] <= tmp)
i++;
A[j] = A[i];
}
A[i] = tmp;
quickSort(A, first, i - 1);
quickSort(A, i + 1, end);
}
}
public void merge(int MAX, int[] a, int[] b, int[] c)//将b[]和c[]进行归并排序,放入a[]数组里面
{
int m = 0, n = 0, k;
for (k = 0; k < MAX; k++)
{
if (m < MAX / 2 && n < MAX / 2)
{
if (b[n] <= c[m])
{
a[k] = b[n];
n++;
}
else
{
a[k] = c[m];
m++;
}
}
if (m == MAX / 2 || n == MAX / 2)
{
if (m == MAX / 2)
a[k] = c[m - 1];
else
a[k] = b[n - 1];
k += 1;
break;
}
}
if (n < MAX / 2)
{
int tem = MAX / 2 - n;
for (int p = 0; p < tem; p++)
{
a[k] = b[n];
n++;
k++;
}
}
else if (m < MAX / 2)
{
int tem = MAX / 2 - m;
for (int q = 0; q < tem; q++)
{
a[k] = c[m];
m++;
k++;
}
}
}
public static int MAX=70000;
public static int MAXN=MAX/2;
public static void main(String[] args) throws InterruptedException {
int buf[]=new int[MAX+2];
int a[]=new int[MAX+2];
int b[]=new int[MAXN+2];
int c[]=new int[MAXN+2];
for(int i=0;i<MAX;i++){
buf[i]=(int)(Math.random()*10+1);
a[i]=buf[i];
//System.out.print(buf[i]+" ");
}
System.out.println();
for(int i=0;i<MAXN;i++){
b[i]=a[i];
c[i]=a[i+MAXN];
}
And thread1=new And(b,0,MAXN-1);
And thread2=new And(c,0,MAXN-1);
long startTime=System.currentTimeMillis();
thread1.start();
thread2.start();
thread1.join();
thread2.join();
And and=new And(a,0,MAX-1);
and.merge(MAX, a, b, c);
long endTime=System.currentTimeMillis();
//for(int i=0;i<MAX;i++){
//System.out.print(a[i]+" ");
//}
System.out.println();
long time1=endTime-startTime;
System.out.println("并行时间="+time1);
startTime=System.currentTimeMillis();
And serial=new And(buf,0,MAX-1);
serial.quickSort(buf,0,MAX-1);
//for(int i=0;i<MAX;i++){
//System.out.print(buf[i]+" ");
//}
System.out.println();
endTime=System.currentTimeMillis();
//System.out.println("串行结果="+sum);
long time2=endTime-startTime;
System.out.println("串行时间="+time2);
System.out.printf("加速比为%.2f",(time2*1.0/time1));
}
}