Java实现快速排序和合并排序

时间:2022-10-13 22:09:06
package sort.com;

import java.util.Arrays;

//合并排序:对数组SR[s...t]的这一部分元素进行排序
public class Merge {
//在静态方法中不能直接调用非静态方法
static void mergeSort(int SR[],int TR[],int s,int t){
//划分数组直到数组元素只有一个
if(s==t)
TR[s] = SR[s];
else{
int TR2[] = new int[SR.length];
int m=(s+t)/2;
mergeSort(SR,TR2,s,m);
mergeSort(SR,TR2,m+1,t);
mergesort(TR2,TR,s,m,t);
}
}
static void mergesort(int SR[],int TR[],int s,int m,int t){
int i=s,j=m+1,k=s;
while(i<=m&&j<=t){
if(SR[i]<SR[j])
TR[k++]=SR[i++];
else
TR[k++]=SR[j++];
}
//将剩下的还未复制到TR数组的元素复制
while(i<=m)
TR[k++]=SR[i++];
while(j<=t)
TR[k++]=SR[j++];
}
public static void main(String[] args) {
int SR[] = new int[]{20,15,36,12,65,8,34};
System.out.println(Arrays.toString(SR));
int TR[] = new int[SR.length];
mergeSort(SR,TR,0,SR.length-1);
System.out.println(Arrays.toString(TR));
}
}
package sort.com;import java.util.Arrays;//快速排序public class Quick {static void quickSort(int A[],int p,int q){if(p<q){//将数组分成3部分:p~r-1,r,r+1~qint r = partition(A,p,q);quickSort(A,p,r-1);quickSort(A,r+1,q);}}static int partition(int A[],int p,int q){//划分主元,将比主元小的元素放在左边,比主元大的放在右边int x = A[p],i=p,j,swap;for(j=p+1;j<=q;j++){if(A[j]<=x){i++;//i指向的是这一轮循环中最后一个比主元小的元素swap=A[i];A[i]=A[j];A[j]=swap;}}swap=A[i];A[i]=A[p];A[p]=swap;return i;//返回本轮循环结束后主元所在的位置,之后主元不需要再参与比较}public static void main(String[] args) {int A[] = new int[]{20,15,36,12,65,8,34};System.out.println(Arrays.toString(A));quickSort(A,0,6);System.out.println(Arrays.toString(A));}}