排序

排序

https://www.nowcoder.com/practice/2baf799ea0594abd974d37139de27896?tpId=196&rp=1&ru=%2Factivity%2Foj&qru=%2Fta%2Fjob-code-total%2Fquestion-ranking

第一种:快排

public int[] MySort (int[] arr) {
        // write code here
        sort(arr,0,arr.length-1);
        return arr;
    }
    private void sort(int[] arr, int start, int end) {
        if(start>=end) return;
        int index = partion(arr,start,end);
        sort(arr,start,index-1);
        sort(arr,index+1,end);
    }
    //找到下标start的元素在数组排完序之后的位置 并替换
    private int partion(int[] arr, int start, int end) {
        int temp=arr[start];
        int left=start;
        int right=end;
        while (left<right){
            //从右往左找第一个小于temp的数
            while (right>left && arr[right]>=temp){
                right--;
            }
            arr[left]=arr[right];
            while (left<right && arr[left]<temp){
                left++;
            }
            arr[right]=arr[left];
        }
        //相遇的位置就是temp的排序后位置
        arr[left]=temp;
        return left;
    }

第二种:归并排序

 public int[] MySort (int[] arr){
        if(arr==null) return arr;
        int[] temp=new int[arr.length];//辅助空间
        sort(arr,0,arr.length-1,temp);
        return arr;
    }

    private void sort(int[] arr, int start, int end,int[] temp) {
        if (start>=end) return;
        int mid=(end-start)/2+start;
        //对左边进行排序
        sort(arr,start,mid,temp);
        //对右边进行排序
        sort(arr,mid+1,end,temp);
        //合并左右两边
        hebing(arr,start,mid,end,temp);
    }
    //将原数组链两个有序的序列进行比较排序并赋值到辅助数组temp,最后再依次赋值回原数组
    private void hebing(int[] arr, int start, int mid, int end, int[] temp) {
        //start--mid
        //mid+1--end
        int i=start;
        int j=mid+1;
        int res = start;
        while (i<=mid && j<=end){
            if(arr[i]<arr[j]){
                temp[res++]=arr[i];
                i++;
            }else {
                temp[res++]=arr[j];
                j++;
            }
        }
        if (i<=mid){
            for(int y=i;y<=mid;y++){
                temp[res++]=arr[y];
            }
        }
        if(j<=end){
            for(int y=j;y<=end;y++){
                temp[res++]=arr[y];
            }
        }
        for (int y=start;y<=end;y++){
            arr[y]=temp[y];
        }
    }
全部评论

相关推荐

10-29 22:30
吉林大学 Java
同专业学长学姐,去互联网大厂的起薪&nbsp;15k+,去国企&nbsp;IT&nbsp;岗的也有&nbsp;12k+,就连去中小厂的都基本&nbsp;13k&nbsp;起步😤&nbsp;我投的传统行业技术岗,拼死拼活拿到&nbsp;1Woffer,本来还挺开心,结果逛了圈牛客直接破防,同是校招生,行业差距怎么就这么大啊!
喵喵喵6_6:应该哪里不对吧,大厂都是20k以上的,10k那种对于985本的学生基本就是点击一下过了笔试就送的,我前两天刚拿了一个11k,笔试完第2天就打电话了,非科班。坏消息是c++岗开这么低真是刷新认知了
校招生月薪1W算什么水平
点赞 评论 收藏
分享
点赞 评论 收藏
分享
酷酷的喜马拉雅山:感觉这比一直在初筛不动的好多了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务