算法学习笔记之计数排序

计数排序属于线性排序的一种,时间复杂度为Θ(n),但不是原址排序,牺牲了一定的空间复杂度

C#实现如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AlgorithmTest
{
    class CountingSort
    {
        public void Counting_Sort ( int[] arr, int k )
        {
            int length = arr.Length;
            //存储结果的数组
            int[] result = new int[length];
            //临时数组,用于记录arr中每个元素出现次数,元素的值对应temp的下标
            int[] temp = new int[k];
            int i = 0;
            //初始化temp数组
            for (i = 0; i < k; i++)
            {
                temp[i] = 0;
            }
            //开始计数,arr中的值每出现一次,temp对应位置的元素值加1
            for (i = 0; i < length; i++)
            {
                temp[arr[i] - 1] = temp[arr[i] - 1] + 1;
            }
            //从前往后,依次将值加到后面一项,这样可以保证temp中每个元素中存储了arr中小于等于当前值的元素个数
            for (i = 1; i < k; i++)
            {
                temp[i] = temp[i] + temp[i-1];
            }
            //依据temp中的值,将arr中每个元素放到result中去,每放一个temp中值要减1,这样为了如果出现相同元素,不会重复写到同一个位置
            for (i = length-1; i >= 0; i--)
            {
                result[temp[arr[i] - 1] - 1] = arr[i];
                temp[arr[i] - 1]--;
            }
        }
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值