快速排序和归并排序

快速排序和归并排序

快速排序

public static void quickSort(int nums[]){
    quick(nums,0,nums.length - 1);
}
public static void quick(int nums[], int begin , int end) {
    if(begin >= end ){
        return;
    }
    int ex = begin;
    int a = begin + 1;
    int b = end;
    while ( a <= b ){
        if( nums[ex] < nums[a]  ){
            int temp = nums[b];
            nums[b] = nums[a];
            nums[a] = temp;
            b--;
        } else {
            int temp = nums[a];
            nums[a] = nums[ex];
            nums[ex] = temp;
            a++;
            ex++;
        }
    }
    quick(nums,begin, ex -1);
    quick(nums,ex + 1, end);
}

归并排序

public static void mergeSort(int nums[]){
    int ex[] = new int[nums.length];
    merge(nums,ex,0,nums.length - 1);

}
public static void merge(int nums[],int ex[], int begin , int end) {
    if ( begin >= end){
        return;
    }
    int mid = (begin + end ) / 2;
    merge(nums,ex,begin,mid);
    merge(nums,ex,mid + 1,end);
    int a = begin;
    int b = mid  + 1;
    int exb = begin;
    while ( a <= mid || b <= end ){
        if ( a > mid ){
            ex[exb] = nums[b];
            exb++;
            b++;
        } else if ( b > end ){
            ex[exb] = nums[a];
            exb++;
            a++;

        } else if ( nums[a] <= nums[b] ){
            ex[exb] = nums[a];
            exb++;
            a++;
        } else  {
            ex[exb] = nums[b];
            exb++;
            b++;
        }
    }
    for(int i = begin ; i<= end ;i++){
        nums[i] = ex[i];
    }
}