P1177 【模板】快速排序 java 洛谷

两种做法,不熟悉归并和快排的建议两个都用去做一下,不过传统快排这题有坑的要注意。最近发现用stream流做简单一些的算法题是真的爽!!!

就比如这题:

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) throws IOException {
        int n = nextInt();
        List<Integer> list = new ArrayList<>();
        while(n-- > 0) {
            list.add(nextInt());
        }
        list.stream().sorted().forEach(num -> out.print(num + " "));
        out.close();
    }
    
    //魔法快读,不懂的小伙伴可以看看我的文章
    //http://t.csdn.cn/zhS6J
    static StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
    static PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));

    public static int nextInt() throws IOException {
        in.nextToken();
        return (int) in.nval;
    }
}

传统归并:

import java.io.*;
import java.util.*;

public class Main {
    static int[] b;
    public static void main(String[] args) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StreamTokenizer st = new StreamTokenizer(br);//当然用Scanner一样的
        PrintWriter pr = new PrintWriter(System.out);
        st.nextToken();int n=(int)st.nval;
        int[] a=new int[n+1];b=new int[n+1];
        for(int i=1;i<=n;i++){
            st.nextToken();
            a[i]=(int)st.nval;
        }
        msort(a,1,n);
        for(int i=1;i<=n;i++)
            pr.write(a[i]+" ");
        pr.flush();
    }
    static void msort(int[] a,int l,int r){
        if(l>=r)return;
        int mid=l+r>>1,i=l,j=mid+1,k=i;
        msort(a,l,mid);msort(a,mid+1,r);
        while(i<=mid&&j<=r){
            if(a[i]<=a[j]) b[k++]=a[i++];
            else           b[k++]=a[j++];
        }
        while(i<=mid)b[k++]=a[i++];
        while(j<=r)b[k++]=a[j++];
        for(int z=l;z<=r;z++)
            a[z]=b[z];
    }
}

虽然stream流很爽,但是算法基础功扎实了以后再使用,才不会走火入魔。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

玛卡左家陇分卡

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值