排序数组 归并和快速

 题目:力扣

class Solution {
    public int[] sortArray(int[] nums) {
        if(nums.length<=1){
            return nums;
        }
        //quicksort(nums,0,nums.length-1);
        mergesort(nums,0,nums.length-1);
        return nums;
    }

    public int Partition(int[] nums,int start, int end){
        int base = nums[start];
        while(end>start){
            while(end>start && nums[end]>=base){
                 end--;
            }
            nums[start]=nums[end];
            while(end>start && nums[start]<=base){
                start++;
            }
            nums[end]= nums[start];
        }
        nums[start]=base;
        return start;
    }

    public void quicksort(int[] nums,int start, int end){
        if(end>start){
            int p = Partition(nums, start,end);
            quicksort(nums,start,p-1);
            quicksort(nums,p+1,end);
        }
    }

    public void mergesort(int[] nums, int start, int end){
        if(start>=end)
            return;
        int mid = (start+end)/2;
        mergesort(nums, start, mid);
        mergesort(nums, mid+1, end);
        int[] temp = new int[end-start+1];
        int first = start;
        int second = mid+1;
        int cur = 0;
        while(first <= mid && second <=end){
            if(nums[first]<nums[second]){
                temp[cur++]=nums[first++];
            }
            else{
                temp[cur++]=nums[second++];
            }
        }
        while(first <= mid){
            temp[cur++]= nums[first++];
        }
        while(second <= end){
            temp[cur++]= nums[second++];
        }
        for (int k = 0; k < temp.length; k++) {             // 合并数组完成,拷贝到原来的数组中
            nums[start+k] = temp[k];
        }
    }
    
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值