算法学习笔记之计数排序

来源:互联网 发布:钢琴键盘软件 编辑:程序博客网 时间:2024/05/10 00:24

计数排序属于线性排序的一种,时间复杂度为Θ(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]--;            }        }    }}