Algorithms-2.1 Elementary Sorts 初级排序算法(选择排序、插入排序、希尔排序)

Elementary Sorts

1 排序介绍(rules of the game)

1.1 示例

  • 给0-1之间的小数升序排序
package Chapter02;

import edu.princeton.cs.algs4.StdOut;
import edu.princeton.cs.algs4.StdRandom;
import edu.princeton.cs.algs4.Insertion;

//Sort random real numbers in ascending order
public class Experiment {
   

        public static void main(String[] args) {
   
            //在命令行输入要生成几个随机数
            int N = Integer.parseInt(args[0]); //将字符串参数解析为带符号的十进制整数
            Double[] a = new Double[N]; //生成含有N个元素的数组a
            for (int i = 0; i < N; i++) {
   
                a[i] = StdRandom.uniform();//Returns a random real number uniformly in [0, 1)
            }
            Insertion.sort(a); //Rearranges the array in ascending order, using the natural order
            for (int i = 0; i < N; i++) {
   
                StdOut.println(a[i]);
            }

        }
}

/*
正常run(不需在terminal):

    public static void main(String[] args) {

            Double[] a = new Double[10];
            for (int i = 0; i < 10; i++) {
                a[i] = StdRandom.uniform();//Returns a random real number uniformly in [0, 1)
            }
            Insertion.sort(a); //升序
            for (int i = 0; i < 10; i++) {
                StdOut.println(a[i]);
            }

        }
 */
  • 文件内容按字母顺序排序
package Chapter02;

import edu.princeton.cs.algs4.In;
import edu.princeton.cs.algs4.Insertion;
import edu.princeton.cs.algs4.StdOut;

//文件内容按字母顺序排序
public class StringSorter {
   
    public static void main(String[] args) {
   
        String[] a = In.readStrings(args[0]);
        Insertion.sort(a);
        for (int i = 0; i < a.length; i++) {
   
            StdOut.println(a[i]);
        }

    }
}

/*
原文件:
bed bug dad yes zoo
now for tip ilk dim
tag jot sob nob sky
hut men egg few jay
owl joy rap gig wee
was wad fee tap tar
dug jam all bad yet

运行结果:
all
bad
bed
bug
dad
dim
dug
egg
fee
few
for
gig
hut
ilk
jam
jay
jot
joy
men
nob
now
owl
rap
sky
sob
tag
tap
tar
tip
wad
was
wee
yes
yet
zoo

 */
  • 文件名按字母排序
package Chapter02;

import edu.princeton.cs.algs4.Insertion;
import edu.princeton.cs.algs4.StdOut;

import java
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值