java实现快速排序,归并排序

//1.快速排序
import java.util.*;


public class Main {
    
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int[] a = new int[n];
        for(int i=0;i<n;i++) {
            a[i] = sc.nextInt();
        }
        qsort(a,0,n-1);
        for(int i=0;i<n;i++) {
            System.out.print(a[i]+" ");
        }
        sc.close();
    }

    private static int getPos(int[] a,int left,int right) {
        int mid = a[right];
        while(left<right) {
            while(left<right && a[left]<=mid) {
                left++;
            }
            a[right] = a[left];
            while(left<right && a[right]>=mid) {
                right--;
            }
            a[left] = a[right];            
        }
        a[left] = mid;
        
        return left;
    }
    private static void qsort(int[] a,int left,int right) {
        
        if(left<right) {
            int mid = getPos(a,left,right);
            qsort(a,left,mid-1);
            qsort(a,mid+1,right);
        }
    }
}
//归并排序
import java.util.*;

public class Main {
    
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int[] a = new int[n];
        for(int i=0;i<n;i++) {
            a[i] = sc.nextInt();
        }
        mergeSort(a,0,n-1);
        for(int i=0;i<n;i++) {
            System.out.print(a[i]+" ");
        }
        sc.close();
    }
    static void mergeSort(int[] a,int start, int end) {
        if(start < end) {
            int pos = (start+end)/2;
            mergeSort(a,start,pos);
            mergeSort(a, pos+1, end);
            merge(a, start, pos, end);
        }
    }
    static void merge(int[] a, int p,int q,int r) {
        int n1 = q - p + 1 + 1;//左边长度
        int n2 = r - q + 1;//右边长度 0 1 3
        int[] L = new int[n1];
        int[] R = new int[n2];
        int i,j;
        for(i=0;i<n1-1;i++) {
            L[i] = a[p+i];
        }
        for(j=0;j<n2-1;j++) {
            R[j] = a[q+j+1];
        }
        L[n1-1] = 1000000;
        R[n2-1] = 1000000;
        i=0; j=0;
        for(int k=p; k<=r;k++) {
            if(L[i] <= R[j]) {
                a[k]=L[i];
                i++;
            }else{
                a[k]=R[j];
                j++;
            }
        }
    }
}

 

posted @ 2019-11-27 23:25  bestwell  阅读(238)  评论(0编辑  收藏  举报