借助辅助空间来排序

import com.google.common.base.Preconditions;

import java.util.Arrays;

/**
 * 借助常数大小的辅助空间来实现时间复杂度为O(n)的排序。
 */
public class SortWithAuxiliarySpace {


    /**
     * 将数组中的数排序,数组中存放的是学生的考试成绩。
     *
     * 分析:
     *  1)目标数组中元素的取值范围为0~100
     *  2)可以使用一个长度为101的辅助数组来存储目标数组中各元素出现的次数:辅助数组中下标为m的元素表示m在目标数组中出现的次数。
     *
     * @param scoreArray
     */
    public static void sort(int[] scoreArray) {

        Preconditions.checkArgument(null!= scoreArray && scoreArray.length > 0);

        // 辅助数组
        int[] timesArray = new int[101];

        Arrays.stream(scoreArray).forEach(score -> {

            if (score < 0 || score > 100) {
                throw new IllegalArgumentException("score out of range");
            }

            timesArray[score]++;    // 将score出现的次数加一
        });

        int index = 0;
        for (int i = 0; i < timesArray.length; i++) {   // i为辅助数组的下标,即 目标数组中的元素

            for (int j = 0; j < timesArray[i]; j++) {    // timesArray[i]表示i在目标数组中出现的次数。
                scoreArray[index] = i;
                index++;
            }

        }
    }


    public static void main(String[] args) {

        int[] scoreArray = {98, 89, 45, 54, 12, 21, 36, 37, 37, 37, 99, 99, 44, 88, 88, 88, 88, 100, 0, 100, 100, 88};
        sort(scoreArray);
        Arrays.stream(scoreArray).forEach(score -> {
            System.out.println(score);
        });
    }

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值