首页 > 试题广场 >

1-10排序算法

[编程题]1-10排序算法
  • 热度指数:4540 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M
  • 算法知识视频讲解
请使用random() 函数,生成 10个随机数,并对它进行升序排序 ,要求有效率。
注意:不允许使用代码库提供的 sort() 之类现成的排序函数。

输出描述:
1
2
2
4
5
5
6
6
8
10

备注:
因为是random产生,所以只要排序对就行
考虑用计数排序,线性时间内完成排序
import java.util.Random;

/**
 * @Author: coderjjp
 * @Date: 2020-05-12 22:56
 * @Description:
 * @version: 1.0
 */
public class Main {
    public static void main(String[] args) {
        Random r = new Random();
        int nums[] = new int[10];
        int hash[] = new int[10];
        for (int i = 0; i < 10; i++){
            nums[i] = r.nextInt(10);
            hash[nums[i]]++;
        }
        for (int i = 0; i < 10; i++){
            while (hash[i] != 0){
                System.out.println(i);
                hash[i]--;
            }
        }
    }
}


发表于 2020-05-12 23:09:40 回复(2)